3 回答

TA贡献1805条经验 获得超9个赞
列名可作为cr.description[0][0]
,cr.description[1][0]
等等。如果你想它正是你展示的格式,你需要做一些工作来提取它,并把它贴在结果集的前面。

TA贡献1848条经验 获得超6个赞
如果您想要的是一个数据框,该数据框具有db表中的数据作为其值,并且数据框列名是您从db中读取的字段名,那么这应该可以满足您的要求:
import psycopg2 as pq
cn = pq.connect('dbname=mydb user=me')
cr = cn.cursor()
cr.execute('SELECT * FROM test1;')
tmp = cr.fetchall()
# Extract the column names
col_names = []
for elt in cr.description:
col_names.append(elt[0])
# Create the dataframe, passing in the list of col_names extracted from the description
df = pd.DataFrame(tmp, columns=col_names)

TA贡献1820条经验 获得超9个赞
您也可以在它上面映射,看起来更好一些:
cursor.execute(open("blah.sql", "r").read())
data = cursor.fetchall()
cols = list(map(lambda x: x[0], cursor.description))
df = DataFrame(data, columns=cols)
添加回答
举报