【问题标题】:Pandas - convert float to int when there are NaN values in the columnPandas - 当列中有 NaN 值时将 float 转换为 int
【发布时间】:2020-10-24 02:55:40
【问题描述】:

我正在尝试在我的 df 列中使用这个衬里将浮点数转换为 int:

df['id'] = df['id'].map(lambda x: int(x))

但有些值是 NaN 会抛出:

ValueError: cannot convert float NaN to integer

我该如何解决这个问题?

【问题讨论】:

  • x.astype('int',errors = 'ignore') 会工作吗?
  • @rhug123 不,nan 仍然存在,并且该列自动转换为浮动。

标签: pandas


【解决方案1】:

NaN 本身是浮动的,不能转换为通常的int。您可以将pd.Int64Dtype() 用于可空整数:

# sample data:
df = pd.DataFrame({'id':[1, np.nan]})

df['id'] = df['id'].astype(pd.Int64Dtype())

输出:

     id
0     1
1  <NA>

另一种选择是使用apply,但随后该列的dtype 将是object 而不是numeric/int:

df['id'] = df['id'].apply(lambda x: x if np.isnan(x) else int(x))

【讨论】:

猜你喜欢
  • 2016-03-12
  • 2021-11-02
  • 2017-01-16
  • 1970-01-01
  • 2020-01-21
  • 2017-03-08
  • 2016-07-19
  • 2014-02-12
相关资源
最近更新 更多