to_sql中的可能AttributeError错误

1 投票
1 回答
1527 浏览
提问于 2025-04-18 01:58

我不太确定在 to_sql(pandas 0.13.1)中这种行为是否是故意的。当我创建一个没有列名的数据框(dataframe),然后尝试将其写入一个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']

那么写入数据库就顺利多了。我实际上想推送到数据库的是真正的多重索引(MultiIndex)数据框,显然有些列是没有标签的。

                   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

1 个回答

3

这个问题出现的原因是,在pandas 0.13.1(及更早版本)中,不支持用数字作为列名。你可以通过在写入sql之前,先做一些处理来解决这个问题(如果你不想改其他名字的话):

df.columns = df.columns.astype(str)

从pandas 0.14开始,sql的功能是基于sqlalchemy的,现在支持用数字作为列名和多重索引。不过,多重索引的列目前还不支持,而且我觉得在sql中应该输出什么也不太清楚。所以,用户需要先去掉一个层级或者把多重索引变平。

撰写回答