【问题标题】:Pandas read sql integer became floatPandas 读取的 sql 整数变为浮点数
【发布时间】:2016-10-14 07:04:39
【问题描述】:

我遇到一个问题,当我使用pandas读取Mysql表时,一些列(参见'to_nlc')曾经是整数变成了浮点数(之后自动添加.0)。 任何人都可以弄清楚吗?还是一些猜测?非常感谢!

【问题讨论】:

    标签: python mysql pandas int


    【解决方案1】:

    如前所述,问题在于 pandas 的整数无法处理 NULL/NA 值。

    您可以将 read_sql_table 替换为 read_sql 并将 NULL 转换为某个整数值(例如 0 或 -1,在您的设置中具有 NULL 意义):

    df = pandas.read_sql("SELECT col1, col2, IFNULL(col3, 0) FROM table", engine)
    

    这里col3在mysql中可以为NULL,如果为NULL则返回0,否则返回col3值。

    或者用小函数助手做同样的事情:

    def read_sql_table_with_nullcast(table_name, engine, null_cast={}):
        """
        table_name - table name
        engine - sql engine
        null_cast - dictionary of columns to replace NULL:
               column name as key value to replace with as value.
               for example {'col3':0} will set all NULL in col3 to 0
        """
        import pandas
        cols = pandas.read_sql("SHOW COLUMNS FROM " + table_name, engine)
        cols_call = [c if c not in null_cast else "ifnull(%s,%d) as %s"%(c,null_cast[c],c) for c in cols['Field']]
        sel = ",".join(cols_call)
        return pandas.read_sql("SELECT " + sel + " FROM " + table_name, engine)
    
    read_sql_table_with_nullcast("table", engine, {'col3':0})
    

    【讨论】:

      【解决方案2】:

      问题是您的数据包含NaN 值,因此int 会自动转换为float

      我想你可以查看NA type promotions:

      当通过重新索引或其他方式将 NA 引入现有 Series 或 DataFrame 时,布尔和整数类型将被提升为不同的 dtype 以存储 NA。下表总结了这些:

      Typeclass   Promotion dtype for storing NAs
      floating    no change
      object      no change
      integer     cast to float64
      boolean     cast to object
      

      虽然这似乎是一个沉重的权衡,但在实践中,我发现在实践中这是一个问题的案例很少。在下一节中对这里的动机进行了一些解释。

      【讨论】:

      • 如何避免这种情况?整数用作标识符,以便转换为浮点数会导致精度错误
      • @HananShteingart - 可以将NaN 替换为0 吗?喜欢df['colname'] = df['colname'].fillna().astype(int)df = df.fillna(0).astype(int)
      • 我已经从 SQL 中得到它作为浮点数。我所做的是将列转换为 sql 查询中的字符串:例如CAST(bigint_column AS VARCHAR) 所以我将它作为数据框中的字符串获取。我不介意它不再是数字,因为该列无论如何都代表一个 ID。
      • @MartinThoma - 老实说不知道,如果使用 integer na 并引发错误,那么就不会。
      猜你喜欢
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2017-12-15
      • 1970-01-01
      • 2012-03-22
      相关资源
      最近更新 更多