Python:pandas.replace 不适用于 np.nan
Python: pandas.replace doesn't work with np.nan
我想用 None
值替换 np.nan
,但出现了奇怪的行为:
>>> import pandas as pd
>>> import numpy as np
>>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
>>> s = s.replace(np.nan, None)
>>> print(s)
0 cat
1 dog
2 dog
3 rabbit
dtype: object
如何将np.nan
替换为'dog'
字符串?我不明白。你能给我解释一下吗?
我发现此代码按预期工作,因此不需要正确的解决方案答案。
s = s.replace({np.nan: None})
第二个参数是none,所以等于s.replace(np.nan)
您可以尝试使用以下方法替换所有的“nan”:df = df.fillna(value='')
,它会将所有 nan 替换为“
”
>>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
When value=None
and to_replace is a scalar, list or tuple, replace
uses the method parameter (default ‘pad’) to do the replacement. So
this is why the ‘a’ values are being replaced by 10 in rows 1 and 2
and ‘b’ in row 4 in this case. The command s.replace('a', None)
is
actually equivalent to s.replace(to_replace='a', value=None, method='pad')
:
>>> s.replace('a', None)
0 10
1 10
2 10
3 b
4 b
dtype: object
我想用 None
值替换 np.nan
,但出现了奇怪的行为:
>>> import pandas as pd
>>> import numpy as np
>>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
>>> s = s.replace(np.nan, None)
>>> print(s)
0 cat
1 dog
2 dog
3 rabbit
dtype: object
如何将np.nan
替换为'dog'
字符串?我不明白。你能给我解释一下吗?
我发现此代码按预期工作,因此不需要正确的解决方案答案。
s = s.replace({np.nan: None})
第二个参数是none,所以等于s.replace(np.nan)
您可以尝试使用以下方法替换所有的“nan”:df = df.fillna(value='')
,它会将所有 nan 替换为“
>>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
When
value=None
and to_replace is a scalar, list or tuple, replace uses the method parameter (default ‘pad’) to do the replacement. So this is why the ‘a’ values are being replaced by 10 in rows 1 and 2 and ‘b’ in row 4 in this case. The commands.replace('a', None)
is actually equivalent tos.replace(to_replace='a', value=None, method='pad')
:>>> s.replace('a', None) 0 10 1 10 2 10 3 b 4 b dtype: object