如何将pandas.Series从dtype转换object为float,并将错误转换为nans ?
自v0.17起,convert_objects不推荐使用。
为了一系列转换为数字,使用pd.to_numeric与errors='coerce'论证。
# Setup.
s = pd.Series(['1','2','3','4','.'])
s
0 1
1 2
2 3
3 4
4 .
dtype: object
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
如果您需要NaN填写,请使用Series.fillna。
pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')
0 1
1 2
2 3
3 4
4 0
dtype: float64
注意,downcast='infer'将尝试在可能的情况下将浮点数向下转换为整数。如果您不想要,请删除参数。
从v0.24 +开始,pandas引入了Nullable Intege