Pandas:为什么数字浮点数的默认列类型?

Pandas: Why is default column type for numeric float?

我正在使用 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

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

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

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

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

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)

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

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

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

更新

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