【问题标题】:Cannot convert non-finite values (NA or inf) to integer [duplicate]无法将非有限值(NA 或 inf)转换为整数 [重复]
【发布时间】:2019-04-02 01:41:35
【问题描述】:

我的数据框看起来像这样

   survived pclass  sex age sibsp   parch   fare    embarked
    0   1   1   female  29.0000 0   0   211.3375    S
    1   1   1   male    0.9167  1   2   151.5500    S
    2   0   1   female  2.0000  1   2   151.5500    S
    3   0   1   male    30.0000 1   2   151.5500    S
    4   0   1   female  25.0000 1   2   151.5500    S

我想将'sex'转换为0、1编码并使用isnull检查列中没有NA

然而,在这一行我收到 ValueError: Cannot convert non-finite values (NA or inf) to integer

df['sex'] = df['sex'].map({'female':0, 'male':1}).astype(int)

有什么建议吗?谢谢!

【问题讨论】:

  • 不,如果想要具有 NaNs 值的整数是有问题的,请检查欺骗。可能的解决方案是逐列删除所有 NaN 行 Sex 或将 NaN 替换为某个整数,如 fillna(2).astype(int)

标签: python dataframe


【解决方案1】:

我认为正确的方法是使用replace 函数

df.replace({'sex':{'female':0, 'male':1}}, inplace=True)

如果你的 df 有 nans,那么你可以用一些值填充它们,例如-1,使用fillna,然后替换其余部分

df.fillna({'sex':-1}, inplace=True)
df.replace({'sex':{'female':0, 'male':1}}, inplace=True)

【讨论】:

    【解决方案2】:

    使用np.where

    例如:

    import numpy as np
    
    df['sex'] = np.where(df['sex'] == 'female', 0, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2017-04-01
      • 2014-04-18
      • 1970-01-01
      相关资源
      最近更新 更多