【问题标题】:pandas convert objects with numbers and nans to ints or floatspandas 将带有数字和 nans 的对象转换为整数或浮点数
【发布时间】:2019-12-30 13:59:54
【问题描述】:

知道类似的案例已经回答了好几次,我还是无法让它工作。

样本数据:

10
5
20

5

6

在我发现之后:

df = df['column_name'].astype(str).astype(int)

如果输入数据中没有 nan,它会起作用。

error: invalid literal for int() with base 10: 'nan'

我也尝试过使用浮点数,但它也会报错

error: could not convert string to float

我错过了什么?

输出可以是任何带有“null”、“nan”、“”的东西,例如:

10
5
20
null
5
null
6

【问题讨论】:

  • 你试过pd.to_numeric(df['column_name'])

标签: pandas dataframe object floating-point int


【解决方案1】:

您可以使用to_numericerrors='coerce' 将浮点数转换为数字,对于整数使用nullable integer data type(pandas 0.24+):

df['column_name'] = pd.to_numeric(df['column_name'], errors='coerce').astype('Int64')
print (df)
   column_name
0           10
1            5
2           20
3          NaN
4            5
5          NaN
6            6

详情

print (pd.to_numeric(df['column_name'], errors='coerce'))
0    10.0
1     5.0
2    20.0
3     NaN
4     5.0
5     NaN
6     6.0
Name: column_name, dtype: float64

【讨论】:

  • 哇,真快。对您的回答只有一个小问题:to_numeric 给了我 "" 而不是您在示例中写的 NaN。正常行为还是我会产生另一个错误?
  • @J.Doe - 你认为是否写入文件?如何测试它?
  • 是的,如果我在 excel 中写入 to_excel,所有没有值的单元格都是空的,没有 NaN 也没有 null ;)
  • @J.Doe - 原因是to_excel 将缺失值替换为空值。
  • 非常感谢! live saver =) 有这么多的答案并不能真正让你明白这一点
猜你喜欢
  • 2021-07-20
  • 2021-08-11
  • 2014-11-15
  • 2021-06-24
相关资源
最近更新 更多