Python熊猫替换为None实际上替换为先前的值

时间:2020-11-04 23:09:07

标签: python pandas

pandas'replace函数按预期将目标值替换为另一个值:

>>> import pandas as pd
>>>
>>>
>>> t = pd.Series([10,20,30])
>>> t
0    10
1    20
2    30
dtype: int64
>>> t.replace(to_replace=20, value=222)
0     10
1    222
2     30
dtype: int64
>>> from numpy import nan; t.replace(to_replace=20, value=nan)
0    10.0
1     NaN
2    30.0
dtype: float64

但是当要求替换为None时,它将替换为先前的值。

>>> t.replace(to_replace=20, value=None)
0    10
1    10
2    30
dtype: int64

这背后的原理是什么?

1 个答案:

答案 0 :(得分:1)

这是因为to_replace是标量,而value是None。该行为在documentation中进行了描述:

当to_replace是标量时用于替换的方法, 列表或元组,值是“无”。

如果您查看code,则默认方法为pad。发生这种情况的原因可能是None通常用于表示缺少参数。