【问题标题】:Pandas: Why is default column type for numeric float?Pandas:为什么数字浮点的默认列类型?
【发布时间】:2016-10-26 11:36:18
【问题描述】:

我将 Pandas 0.18.1 与 python 2.7.x 一起使用。我有一个我首先阅读的空数据框。我看到这些列的类型是object,这没关系。当我分配一行数据时,数值类型更改为float64。我期待intint64。为什么会这样?

有没有办法设置一些全局选项让 Pandas 知道对于数值,除非数据有 .,否则默认将它们视为 int?比如[0 1.0, 2.],第一列是int,其他两列是float64?

例如:

>>> df = pd.read_csv('foo.csv', engine='python', keep_default_na=False)
>>> print df.dtypes
bbox_id_seqno    object
type             object
layer            object
ll_x             object
ll_y             object
ur_x             object
ur_y             object
polygon_count    object
dtype: object
>>> df.loc[0] = ['a', 'b', 'c', 1, 2, 3, 4, 5]
>>> print df.dtypes
bbox_id_seqno     object
type              object
layer             object
ll_x             float64
ll_y             float64
ur_x             float64
ur_y             float64
polygon_count    float64
dtype: object

【问题讨论】:

    标签: python csv pandas nan na


    【解决方案1】:

    Pandas 无法将 NaN 值存储在整数列中。

    这使得float 成为数据存储的明显默认选择,因为一旦出现缺失值,Pandas 就必须更改整个列的数据类型。缺失值在实践中经常出现。

    至于为什么,这是继承自 Numpy 的限制。基本上,Pandas 需要留出一个特定的位模式来表示NaN。这对于浮点数来说很简单,并且在 IEEE 754 标准中定义。对于固定宽度的整数,这样做更尴尬,效率更低。

    更新

    pandas 0.24 中令人兴奋的消息。 IntegerArray 是一项实验性功能,但可能会使我的原始答案过时。因此,如果您在 2019 年 2 月 27 日或之后阅读本文,请查看 the docs 了解该功能。

    【讨论】:

      【解决方案2】:

      原因几乎可以肯定与灵活性和速度有关。仅仅因为 Pandas 到目前为止只在该列中看到了一个整数,并不意味着您以后不会尝试添加一个浮点数,这将需要 Pandas 返回并更改所有该列的类型。浮点数是最健壮/灵活的数值类型。

      没有覆盖该行为的全局方法(我知道),但您可以使用 astype 方法修改单个 DataFrame。

      http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html

      【讨论】:

        【解决方案3】:

        如果您正在读取一个空的数据框,您可以在读取后显式转换每列的类型。

        dtypes = {
            'bbox_id_seqno': object,
            'type': object,
            'layer': object,
            'll_x': int,
            'll_y': int,
            'ur_x': int,
            'ur_y': int,
            'polygon_count': int
        }
        
        
        df = pd.read_csv('foo.csv', engine='python', keep_default_na=False)
        
        for col, dtype in dtypes.iteritems():
            df[col] = df[col].astype(dtype)
        
        df.loc[0] = ['a', 'b', 'c', 1, 2, 3, 4, 5]
        
        >>> df.dtypes
        bbox_id_seqno    object
        type             object
        layer            object
        ll_x              int64
        ll_y              int64
        ur_x              int64
        ur_y              int64
        polygon_count     int64
        dtype: object
        

        如果您不知道空数据框中的列名,您可以先将所有内容指定为 int,然后让 Pandas 对其进行排序。

        for col in df:
            df[col] = df[col].astype(int)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多