pandas read_sql 在列名称中删除点

pandas read_sql drops dot in column names

这是错误还是我做错了什么? 我创建了一个 df,把它放在 sql table 中,df 和 table 有一个带点的列。 现在,当我从 sql table 读取 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

解决方案是将 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? and 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