我不确定 to_sql 中是否存在此行为(pandas 0.13.1)的目的是。当我创建一个没有列名的数据框并尝试写入 SQL 数据库时
dfi = DataFrame(randn(3, 10))
dfi.to_sql(name = to_table, con=connection, flavor='mysql', if_exists='replace')
我收到以下错误:
/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/sql.pyc in get_schema(frame, name, flavor, keys)
308 lookup_type = lambda dtype: get_sqltype(dtype.type, flavor)
309 # Replace spaces in DataFrame column names with _.
--> 310 safe_columns = [s.replace(' ', '_').strip() for s in frame.dtypes.index]
311 column_types = lzip(safe_columns, map(lookup_type, frame.dtypes))
312 if flavor == 'sqlite':
AttributeError: 'numpy.int64' object has no attribute 'replace'
如果我设置列标题
dfi.columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
,
写入数据库很顺利。我试图插入数据库的真正数据框是一个多索引数据框,显然有些列没有标记。
id month values
stats count mean std min 25% 50% 75% max
0 1 Jan 2108 233.373102 107.521779 33 160.00 209.0 275.00 744.0
1 1 Feb 1920 255.720573 111.454035 45 175.00 230.0 318.25 750.0
2 1 Mar 2108 295.674810 113.522911 59 219.00 277.0 346.00 803.0
3 1 Apr 2017 287.206247 99.577189 112 216.00 267.0 342.00 876.0
4 1 May 2077 224.939336 80.810044 93 168.00 207.0 259.00 627.0
最佳答案
这不起作用的原因是 pandas 0.13.1(及更低版本)的 sql 版本不支持整数列名称。在将其写入 sql 之前,您可以使用(如果您不想提供其他名称)轻松解决此问题:
df.columns = df.columns.astype(str)
从pandas 0.14开始,sql函数基于sqlalchemy,现在支持整数列名和多索引索引。
尚不支持多索引列,但也不清楚我认为sql中应该输出什么?因此,由用户决定首先降低一个级别还是压平多索引。
关于python - to_sql 中可能存在 AttributeError 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22952832/