意外的pandas.Series.replace()行为 [英] Unexpected pandas.Series.replace() behavior
问题描述
给出这个-
import pandas as pd
s = pd.Series(['', '1', '2', '', '4', '', '6'])
为什么这样做-
s.replace('', None).values
结果-
array(['', '1', '2', '2', '4', '4', '6'], dtype=object)
我什么时候希望-
array([None, '1', '2', None, '4', None, '6'], dtype=object)
推荐答案
在其中使用None是有问题的.如果您为参数传递无",它将使用该参数的默认值( docs ):
The use of None is problematic there. If you pass None for an argument, it will use the default value for that (docs):
没有
types.NoneType的唯一值.没有一个经常被用来 表示缺少值,例如默认参数不存在时 传递给函数.
The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.
所以s.replace('', None)
与s.replace('')
相同.显然,不传递任何值时的默认操作是向前填充Series.相反,您可以使用np.nan:
So s.replace('', None)
is the same as s.replace('')
. Apparently the default action when no value is passed is to forward fill the Series. Instead, you can use np.nan:
pd.Series(['', '1', '2', '', '4', '', '6']).replace('', np.nan)
Out:
0 NaN
1 1
2 2
3 NaN
4 4
5 NaN
6 6
dtype: object
或通过字典:
s.replace({'': None})
Out:
0 None
1 1
2 2
3 None
4 4
5 None
6 6
dtype: object
这篇关于意外的pandas.Series.replace()行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!