![](/img/trans.png)
[英]How to convert tuple of tuples to pandas.DataFrame in Python?
[英]How to turn tuple of tuples in unicode to pandas dataframe in python
所以我连接到数据库并使用fetchall()提取数据
cursor = connection.cursor()
sql = """
SELECT name, n
from table
"""
cursor.execute(sql)
rows = cursor.fetchall(
)
我的行导致元组的元组,我试图将其发送到具有列名称的数据框
我尝试在下面使用,但是
df = pd.DataFrame(rows, columns=['name', 'n'])
但出现错误: DataFrame构造函数未正确调用!
行((u'a',1.0),(u'b',2.0),(u'c',3.0))
该值以unicode表示,但我只希望我的数据框如下所示,任何建议将不胜感激。
您可以将元组转换为带有list(rows)
>>> rows = ((u'a', 1.0), (u'b', 2.0), (u'c', 3.0))
>>> df = pd.DataFrame(list(rows), columns=['name', 'n'])
>>> df
name n
0 a 1
1 b 2
2 c 3
你为什么不只使用pd.read_sql
:
sql = "SELECT name, n from table"
df = pd.read_sql(sql, connection)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.