【问题标题】:cannot convert nan to int (but there are no nans)无法将 nan 转换为 int(但没有 nan)
【发布时间】:2017-06-18 12:17:09
【问题描述】:

我有一个数据框,其中有一列要转换为 int 的浮点数:

> df['VEHICLE_ID'].head()
0    8659366.0
1    8659368.0
2    8652175.0
3    8652174.0
4    8651488.0

理论上我应该可以使用:

> df['VEHICLE_ID'] = df['VEHICLE_ID'].astype(int)

但我明白了:

Output: ValueError: Cannot convert NA to integer

但我很确定这个系列中没有 NaN:

> df['VEHICLE_ID'].fillna(999,inplace=True)
> df[df['VEHICLE_ID'] == 999]
> Output: Empty DataFrame
Columns: [VEHICLE_ID]
Index: []

发生了什么事?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    基本上错误是告诉你NaN 值,我将说明为什么你的尝试没有揭示这一点:

    In [7]:
    # setup some data
    df = pd.DataFrame({'a':[1.0, np.NaN, 3.0, 4.0]})
    df
    Out[7]:
         a
    0  1.0
    1  NaN
    2  3.0
    3  4.0
    

    现在尝试投射:

    df['a'].astype(int)
    

    这引发了:

    ValueError: Cannot convert NA to integer
    

    但后来你尝试了这样的事情:

    In [5]:
    for index, row in df['a'].iteritems():
        if row == np.NaN:
            print('index:', index, 'isnull')
    

    这什么也没打印,但是NaN 不能像这样使用相等来计算,事实上它有一个特殊的属性,当与自身比较时它会返回False

    In [6]:
    for index, row in df['a'].iteritems():
        if row != row:
            print('index:', index, 'isnull')
    
    index: 1 isnull
    

    现在它会打印该行,您应该使用isnull 以提高可读性:

    In [9]:
    for index, row in df['a'].iteritems():
        if pd.isnull(row):
            print('index:', index, 'isnull')
    
    index: 1 isnull
    

    那该怎么办?我们可以删除行:df.dropna(subset='a'),或者我们可以使用fillna替换:

    In [8]:
    df['a'].fillna(0).astype(int)
    
    Out[8]:
    0    1
    1    0
    2    3
    3    4
    Name: a, dtype: int32
    

    【讨论】:

      【解决方案2】:

      当您的系列包含浮点数和 nan 并且您想要转换为整数时,当您尝试将浮点数转换为 numpy 整数时会出现错误,因为存在 na 值。

      不要这样做:

      df['VEHICLE_ID'] = df['VEHICLE_ID'].astype(int)
      

      从 pandas >= 0.24 现在有一个内置的 pandas 整数。这确实允许整数nan。注意'Int64' 中的大写。这是 pandas 整数,而不是 numpy 整数。

      所以,请这样做:

      df['VEHICLE_ID'] = df['VEHICLE_ID'].astype('Int64')
      

      更多关于 pandas 整数 na 值的信息:
      https://pandas.pydata.org/pandas-docs/stable/user_guide/gotchas.html#nan-integer-na-values-and-na-type-promotions

      【讨论】:

      • 从现在开始,这应该是 IMO 的正确答案,因为此解决方案在将实际浮点数转换为整数时返回 DataFrame NaN 的原样。但要注意Int64 中的大写字母I。如果您尝试 int64 而不是 Int64 它仍然会给出相同的错误。
      猜你喜欢
      • 2016-03-12
      • 1970-01-01
      • 2019-12-26
      • 2021-11-16
      • 2023-01-20
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      相关资源
      最近更新 更多