猿问

Python Psycopg2 Postgres选择包含字段名称的列

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


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


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)]

谢谢


慕仙森
浏览 486回答 3
3回答

Cats萌萌

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

慕勒3428872

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

慕妹3146593

您也可以在它上面映射,看起来更好一些:cursor.execute(open("blah.sql", "r").read())data = cursor.fetchall()cols = list(map(lambda x: x[0], cursor.description))df = DataFrame(data, columns=cols)
随时随地看视频慕课网APP

相关分类

Python
我要回答