pandas 系列替换为回填替代品

问题描述 投票:0回答:1

pandas.Series.replace的文档包含一个示例:

>> import pandas as pd
>> s = pd.Series([1, 2, 3, 4, 5])
>> s.replace([1, 2], method='bfill')
0    3
1    3
2    3
3    4
4    5
dtype: int64

但现在会产生警告:

FutureWarning:Series.replace 中的“method”关键字已弃用 并将在未来版本中删除。

那么获得示例中所述的相同结果的替代方法是什么?

python pandas
1个回答
0
投票

获得相同结果的替代代码可能是:

>> import pandas as pd
>> import numpy as np
>> s = pd.Series([1, 2, 3, 4, 5])
>> s.where(~s.isin([1,2]), np.nan).bfill().astype(int)
0    3
1    3
2    3
3    4
4    5
dtype: int64

replace
的其他用例中,其参数是标量而不是列表,例如:

>> s.replace(2, method='bfill')

替代方案是:

>> s.where(s!=2, np.nan).bfill().astype(int)
© www.soinside.com 2019 - 2024. All rights reserved.