我想要一种从选定的列名直接生成列标签的通用方法,并且记得python的psycopg2模块支持这一特性。
当前回答
摘自Mark Lutz的《Programming Python》:
curs.execute("Select * FROM people LIMIT 0")
colnames = [desc[0] for desc in curs.description]
其他回答
你可以做的另一件事是创建一个游标,你可以通过它们的名字引用你的列(这是一个需要,导致我在第一个地方到这个页面):
import psycopg2
from psycopg2.extras import RealDictCursor
ps_conn = psycopg2.connect(...)
ps_cursor = psql_conn.cursor(cursor_factory=RealDictCursor)
ps_cursor.execute('select 1 as col_a, 2 as col_b')
my_record = ps_cursor.fetchone()
print (my_record['col_a'],my_record['col_b'])
>> 1, 2
我注意到你必须在查询后使用cursor.fetchone()来获取cursor.description中的列列表(即在[desc[0] for desc in curs.description])
如果你想获得一个已经关联列标头的pandas数据帧,试试这个:
import psycopg2, pandas
con=psycopg2.connect(
dbname=DBNAME,
host=HOST,
port=PORT,
user=USER,
password=PASSWORD
)
sql = """
select * from x
"""
d = pandas.read_sql_query(sql,con)
con.close()
print(type(d))
print(pandas.DataFrame.head(d))
摘自Mark Lutz的《Programming Python》:
curs.execute("Select * FROM people LIMIT 0")
colnames = [desc[0] for desc in curs.description]
#!/usr/bin/python
import psycopg2
#note that we have to import the Psycopg2 extras library!
import psycopg2.extras
import sys
def main():
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
# print the connection string we will use to connect
print "Connecting to database\n ->%s" % (conn_string)
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object, you can use this query to perform queries
# note that in this example we pass a cursor_factory argument that will
# dictionary cursor so COLUMNS will be returned as a dictionary so we
# can access columns by their name instead of index.
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# tell postgres to use more work memory
work_mem = 2048
# by passing a tuple as the 2nd argument to the execution function our
# %s string variable will get replaced with the order of variables in
# the list. In this case there is only 1 variable.
# Note that in python you specify a tuple with one item in it by placing
# a comma after the first variable and surrounding it in parentheses.
cursor.execute('SET work_mem TO %s', (work_mem,))
# Then we get the work memory we just set -> we know we only want the
# first ROW so we call fetchone.
# then we use bracket access to get the FIRST value.
# Note that even though we've returned the columns by name we can still
# access columns by numeric index as well - which is really nice.
cursor.execute('SHOW work_mem')
# Call fetchone - which will fetch the first row returned from the
# database.
memory = cursor.fetchone()
# access the column by numeric index:
# even though we enabled columns by name I'm showing you this to
# show that you can still access columns by index and iterate over them.
print "Value: ", memory[0]
# print the entire row
print "Row: ", memory
if __name__ == "__main__":
main()
推荐文章
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置