【问题标题】:How to turn tuple of tuples in unicode to pandas dataframe in python如何将unicode中的元组元组转换为python中的pandas数据框
【发布时间】:2015-03-18 14:49:50
【问题描述】:

所以我连接到数据库并使用 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 ,但我只希望我的数据框如下所示,任何建议都将不胜感激。

【问题讨论】:

标签: python unicode pandas


【解决方案1】:

你为什么不直接使用pd.read_sql:

sql = "SELECT name, n from table"
df = pd.read_sql(sql, connection)

【讨论】:

  • 这正是我想要的。谢谢。
【解决方案2】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-19
    • 2019-08-14
    • 2022-01-09
    • 2021-11-14
    • 2020-12-13
    • 2012-04-03
    • 1970-01-01
    • 2020-09-21
    相关资源
    最近更新 更多