我想要一种从选定的列名直接生成列标签的通用方法,并且记得python的psycopg2模块支持这一特性。
当前回答
我也曾经面临过类似的问题。我用一个简单的技巧来解决这个问题。 假设您在一个列表中有这样的列名
col_name = ['a', 'b', 'c']
然后你就可以跟着做了
for row in cursor.fetchone():
print zip(col_name, row)
其他回答
执行SQL查询后,编写2.7中编写的python脚本
total_fields = len(cursor.description)
fields_names = [i[0] for i in cursor.description
Print fields_names
我也曾经面临过类似的问题。我用一个简单的技巧来解决这个问题。 假设您在一个列表中有这样的列名
col_name = ['a', 'b', 'c']
然后你就可以跟着做了
for row in cursor.fetchone():
print zip(col_name, row)
如果你想从db查询中获得一个命名元组obj,你可以使用下面的代码片段:
from collections import namedtuple
def create_record(obj, fields):
''' given obj from db returns named tuple with fields mapped to values '''
Record = namedtuple("Record", fields)
mappings = dict(zip(fields, obj))
return Record(**mappings)
cur.execute("Select * FROM people")
colnames = [desc[0] for desc in cur.description]
rows = cur.fetchall()
cur.close()
result = []
for row in rows:
result.append(create_record(row, colnames))
这允许您访问记录值,如果他们是类属性,即。
记录。id、记录。other_table_column_name等等。
或者更短
from psycopg2.extras import NamedTupleCursor
with cursor(cursor_factory=NamedTupleCursor) as cur:
cur.execute("Select * ...")
return cur.fetchall()
如果你想把你所有的数据放在一个带列名的Pandas数据框架中:
cur.execute("select * from tablename")
datapoints = cur.fetchall()
cols = [desc[0] for desc in cur.description]
df = pd.DataFrame((datapoints) , columns=[cols])
如果你想获得一个已经关联列标头的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))
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录