pandas 将带有数字和 nan 的对象转换为整数或浮点数

pandas convert objects with numbers and nans to ints or floats

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

示例数据:

10
5
20

5

6

在我弄明白之后:

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

如果输入数据中没有 nans,它就可以工作。

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

我也曾尝试使用 float 代替,但它也给出了错误

error: could not convert string to float

我错过了什么?

输出可以是带有 "null"、"nan"、"" 的任何内容,例如:

10
5
20
null
5
null
6

您可以使用 to_numeric and errors='coerce' for floats in columns and for integers use 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