给定一个系列
s = pd.Series([1.1, 1.2, np.nan])
s
0 1.1
1 1.2
2 NaN
dtype: float64
如果需要将 NaN 转换为 None(例如,使用镶木地板),那么我希望
0 1.1
1 1.2
2 None
dtype: object
我会假设Series.replace
这是执行此操作的明显方法,但该函数返回的内容如下:
s.replace(np.nan, None)
0 1.1
1 1.2
2 1.2
dtype: float64
NaN 是向前填充的,而不是被替换的。正在经历docs https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html,我看到如果第二个参数是 None,那么第一个参数应该是字典。基于此,我预计replace
按预期替换,或引发异常。
我相信这里的解决方法是
pd.Series([x if pd.notna(x) else None for x in s], dtype=object)
0 1.1
1 1.2
2 None
dtype: object
这很好。但我想了解为什么会发生这种行为,是否有记录,或者它是否只是一个错误,我必须清除我的 git 配置文件并在问题跟踪器上记录一个......有什么想法吗?
此行为在文档中method
范围:
method : {‘pad’, ‘ffill’, ‘bfill’, None}
The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.
所以在你的例子中to_replace
is a scalar, and value
is None
。默认的方法是pad
,来自文档fillna https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html:
pad / ffill: propagate last valid observation forward to next valid
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)