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