【问题标题】:Possible AttributeError bug in to_sqlto_sql 中可能的 AttributeError 错误
【发布时间】:2014-04-09 04:31:04
【问题描述】:

我不确定to_sql (pandas 0.13.1) 中的这种行为是否有意。当我创建一个没有列名的数据框并尝试写入 sql db

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

【问题讨论】:

  • 我也找到了this,但我不知道这个问题是如何解决的。
  • mi 列(以及 0.13.1 中的索引)不受支持。

标签: python sql pandas


【解决方案1】:

这不起作用的原因是因为在 pandas 0.13.1(及以下)的 sql 版本中不支持整数列名。在将其写入 sql 之前,您可以通过(如果您不想给出其他名称)轻松解决此问题:

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

从pandas 0.14开始,sql函数基于sqlalchemy,现在支持整数列名和多索引索引。
尚不支持多索引列,但我认为sql中的输出应该是什么也不清楚?因此,由用户首先降低一个级别或展平多索引。

【讨论】:

    猜你喜欢
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多