Python psycopg2 postgres选择包含字段名的列

2024-05-31 23:46:17 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我想从数据库中获取一个表,但是要包含字段名,这样我就可以从列标题中使用它们,例如熊猫,在那里我不一定提前知道所有字段名

如果我的数据库看起来像

table test1

 a | b | c 
---+---+---
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3

我该怎么做

import psycopg2 as pq
cn = pq.connect('dbname=mydb user=me')
cr = cn.cursor()
cr.execute('SELECT * FROM test1;')
tmp = cr.fetchall()
tmp

使tmp显示

[('a','b','c'),(1,2,3),(1,2,3),(1,2,3),(1,2,3),(1,2,3)]

谢谢


Tags: import数据库标题asconnecttablecnpsycopg2
3条回答

如果您想要的是一个数据帧,其中db表中的数据作为其值,而dataframe列名是您从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)

列名可以是cr.description[0][0]cr.description[1][0]等。如果您希望它与显示的格式完全相同,则需要做一些工作来提取它并将其粘贴到结果集前面。

你也可以在上面画一幅看起来更好的地图:

cursor.execute(open("blah.sql", "r").read())
data = cursor.fetchall()
cols = list(map(lambda x: x[0], cursor.description))
df = DataFrame(data, columns=cols)

相关问题 更多 >