首页 > 解决方案 > 为什么 pandas.Series.replace() 在版本之间有不同的功能?

问题描述

问题pandas.Series.replace()成功将值替换bool为版本中的浮点数0.24.2。在版本中运行相同的代码行1.1.3会产生不同的结果。

示例代码

使用0.24.2

import pandas
pd.__version__ # 0.24.2
a = pd.Series([True, False, False, True])
a
0  True
1  False
2  False
3  True
dtype: bool
a.replace(True, 1.2).replace(False, 1)
0   1.2
1   1.0
2   1.0
3   1.2
dtype: float64

使用1.1.3

import pandas
pd.__version__ # 1.1.3
a = pd.Series([True, False, False, True])
a
0  True
1  False
2  False
3  True
dtype: bool
a.replace(True, 1.2).replace(False, 1)
0   1.2
1   0.0
2   0.0
3   1.2
dtype: float64

我也尝试了与我在这里找到的类似的语法:https ://github.com/pandas-dev/pandas/pull/6339 ,但这会产生不同的结果。

a.replace({True: 1.2, False: 1})
0   1
1   1
2   1
3   1
dtype: float64

我可以使用下面的代码成功更改它,但没有发现任何有关功能更改的信息。额外的.astype(int)似乎没有必要。

a.astype(int).replace({1: 1.2, 0: 1})
0   1.2
1   1.0
2   1.0
3   1.2
dtype: float64

标签: pythonpandas

解决方案


主要版本(0.xx 与 1.xx)预计不会向后兼容。事实上,即使是次要版本和补丁版本,开发版本 (0.xx) 也不保证向后兼容。

语义版本控制

如果将任何向后不兼容的更改引入公共 API,则必须增加主要版本 X (Xyz | X > 0)。它还可能包括次要和补丁级别更改。当主要版本增加时,补丁和次要版本必须重置为 0。


推荐阅读