解决办法就是通过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 可能将列名存储为“表名.列名”),请参见例如sqlalchemy+sqlite 去除带点的列名? https://stackoverflow.com/questions/10345910/sqlalchemysqlite-stripping-column-names-with-dots and
这似乎是一个错误,但不一定在 pandas 中read_sql
函数,因为这依赖于keys
SQLAlchemy ResultProxy 对象的方法来确定列名称。这似乎截断了列名:
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