【问题标题】:Why column of int and NaN has float type [duplicate]为什么 int 和 NaN 的列具有浮点类型 [重复]
【发布时间】:2023-03-29 03:09:01
【问题描述】:

我有这个数据框:

data = {'one': pd.Series([1,2,3], index=['a','c','d'], dtype='i4')
        'two': pd.Series([4,7,2,2], index=['a','b','c','d'])}

pd.DataFrame(data)

我得到以下输出

    one two
a   1.0 4

b   NaN 7

c   2.0 2

d   3.0 2

【问题讨论】:

    标签: python pandas numpy series


    【解决方案1】:

    由于NaN 的存在,np.nan 类型是浮点类型。

    在列one 中的索引b 处提供一些其他值

    或者您可以稍后使用

    将其删除
    df.one = df.one.fillna(what_ever_value)
    df.one = df.one.astype(int)
    

    但请确保首先删除 NaN 值。

    【讨论】:

      【解决方案2】:

      在 Pandas / NumPy 中,NaNfloat

      assert type(np.nan) == float
      

      Pandas 为系列设置 dtype 以容纳所有值,如 explained in the docs

      注意:处理异构数据时,将选择生成的 ndarray 的 dtype 以容纳所有数据 涉及。例如,如果涉及字符串,结果将是 对象数据类型。如果只有浮点数和整数,则结果 数组将是 float dtype。

      由于float 系列可以容纳NaNint 值,而int 系列不能容纳NaN,因此您的系列将具有dtype float

      另见Why is NaN considered as a float?

      【讨论】:

        【解决方案3】:

        因为NaN在列中,

        NaN 是一个浮点数,所以,

        >>> import numpy as np
        >>> type(np.nan)
        <class 'float'>
        >>> 
        

        这是一个浮点数,因为它有效:

        >>> float('NaN')
        nan
        >>> 
        

        列中的所有内容都应该是浮点数

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-10
          • 1970-01-01
          • 1970-01-01
          • 2011-05-10
          • 2011-04-05
          • 2018-07-11
          • 1970-01-01
          • 2023-01-31
          相关资源
          最近更新 更多