【问题标题】:pandas read_sql drops dot in column namespandas read_sql 在列名中删除点
【发布时间】:2015-02-04 19:05:02
【问题描述】:

这是一个错误还是我做错了什么? 我创建了一个 df,把它放在一个 sql 表中,df 和表中有一个带有点的列。 现在,当我从 sql 表中读取 df 时,列名不一样了。 我写了一小段代码,以便人们可以测试它。

import sqlalchemy
import pandas as pd
import numpy as np

engine = sqlalchemy.create_engine('sqlite:///test.sqlite')
dfin = pd.DataFrame(np.random.randn(10,2), columns=['column with a . dot', 'without'])
print(dfin)
dfin.to_sql('testtable', engine, if_exists='fail')


tables = engine.table_names()
for table in tables:
    sql = 'SELECT t.* FROM "' + table + '" t'
    dfout = pd.read_sql(sql, engine)
    print(dfout.columns)
    print dfout

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    解决方案是将sqlite_raw_colnames=True 传递给您的引擎

    In [141]: engine = sqlalchemy.create_engine('sqlite:///', execution_options={'sqlite_raw_colnames':True})
    
    In [142]: dfin.to_sql('testtable', engine, if_exists='fail')
    
    In [143]: pd.read_sql("SELECT * FROM testtable", engine).head()
    Out[143]:
       index  column with a . dot   without
    0      0             0.213645  0.321328
    1      1            -0.511033  0.496510
    2      2            -1.114511 -0.030571
    3      3            -1.370342  0.359123
    4      4             0.101111 -1.010498
    

    SQLAlchemy 会故意去除点(在某些情况下,SQLite 可能会将列名存储为“tablename.colname”),参见例如sqlalchemy+sqlite stripping column names with dots?https://groups.google.com/forum/?hl=en&fromgroups#!topic/sqlalchemy/EqAuTFlMNZk


    这似乎是一个错误,但不一定在 pandas read_sql 函数中,因为这依赖于 SQLAlchemy ResultProxy 对象的 keys 方法来确定列名。这似乎截断了列名:

    In [15]: result = engine.execute("SELECT * FROM testtable")
    
    In [16]: result.keys()
    Out[16]: [u'index', u' dot', u'without']
    

    所以问题是这是否是 SQLAlchemy 中的一个错误,或者 pandas 应该采取一种解决方法(例如使用给出正确名称的result.cursor.description

    目前,您还可以使用 sqlite 回退模式,使用 DBAPI 连接而不是 SQLAlchemy 引擎(因为这依赖于 cursor.description,这里使用了正确的列名:

    In [20]: con = sqlite3.connect(':memory:')
    
    In [21]: dfin.to_sql('testtable', con, if_exists='fail')
    
    In [22]: pd.read_sql("SELECT * FROM testtable", con).head()
    Out[22]:
       index  column with a . dot   without
    0      0             0.213645  0.321328
    1      1            -0.511033  0.496510
    2      2            -1.114511 -0.030571
    3      3            -1.370342  0.359123
    4      4             0.101111 -1.010498
    

    【讨论】:

    • 太棒了!我自己找不到,很高兴这里有你这样的人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2016-12-24
    • 2020-09-29
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多