Python psycopg2 postgres选择包括字段名称的列

Tah*_*sha 5 python postgresql psycopg2

嗨,我想从数据库中获取一个表,但是包含字段名称,以便我可以在例如Pandas的列标题中使用它们,我不一定事先知道所有的字段名称

所以如果我的数据库看起来像

table test1

 a | b | c 
---+---+---
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3
 1 | 2 | 3
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

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

就像tmp所示

[('a','b','c'),(1,2,3),(1,2,3),(1,2,3),(1,2,3),(1,2,3)]
Run Code Online (Sandbox Code Playgroud)

谢谢

Pet*_*aut 8

列名可作为cr.description[0][0]cr.description[1][0]等等。如果你想它正是你展示的格式,你需要做一些工作来提取它,并把它贴在结果集的前面。


EdT*_*ech 7

如果你想要的是一个数据帧,其中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)
Run Code Online (Sandbox Code Playgroud)


小智 7

你也可以映射它看起来更好一点:

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


小智 6

您可以使用两个循环情况,而不使用 pandas:

temp = []
for x in result:
    temp2 = {}
    c = 0
    for col in cursor.description:
        temp2.update({str(col[0]): x[c]})
        c = c+1
    temp.append(temp2)
print(temp)
Run Code Online (Sandbox Code Playgroud)

这将打印这样的内容:

[{'column1':'foo1','column2':'foo1'},{'column1':'foo2','column2':'foo2'},...]
Run Code Online (Sandbox Code Playgroud)

我希望这对你有帮助!干杯