pandas 将具有数字和nan的对象转换为int或float [英] pandas convert objects with numbers and nans to ints or floats
本文介绍了 pandas 将具有数字和nan的对象转换为int或float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
知道类似的案例已经被回答了好几次了,我还是无法使它生效。
with the knowledge that similar cases have been answered several times I couldn't make it work anyway.
样本数据:
10
5
20
5
6
在我弄清楚以下内容之后:
after i figured out that with:
df = df['column_name'].astype(str).astype(int)
如果输入数据中没有nans,它将起作用。
it would work if there wasn't nans in the input data.
error: invalid literal for int() with base 10: 'nan'
我也尝试过使用float,但同样会出现错误
Also I did try to use float instead but it gives an error as well
error: could not convert string to float
我想念什么?
输出可以是带有 null, nan,的任何内容,例如:
output can be anything with "null", "nan", "" for example:
10
5
20
null
5
null
6
推荐答案
您可以使用 to_numeric
和 errors ='coerce'
对于列中的浮点数和整数使用 可空整数数据类型
(熊猫0.24 +):
You can convert to numeric with 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
这篇关于 pandas 将具有数字和nan的对象转换为int或float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文