pandas.Series.case_when#

Series.case_when(caselist)[源代码]#

替换条件为 True 的值。

Parameters:
caselist条件和预期替换的元组列表

形式为: (condition0, replacement0), (condition1, replacement1), …。condition 应为一维布尔数组类对象或可调用对象。如果 condition 是可调用对象,则将在 Series 上计算它,并应返回一个布尔 Series 或数组。该可调用对象不得更改输入 Series(尽管 pandas 不会检查它)。replacement 应为一维数组类对象、标量或可调用对象。如果 replacement 是可调用对象,则将在 Series 上计算它,并应返回一个标量或 Series。该可调用对象不得更改输入 Series(尽管 pandas 不会检查它)。

在 2.2.0 版本加入.

Returns:
Series

参见

Series.mask

在条件为 True 的位置替换值。

Examples

>>> c = pd.Series([6, 7, 8, 9], name='c')
>>> a = pd.Series([0, 0, 1, 2])
>>> b = pd.Series([0, 3, 4, 5])
>>> c.case_when(caselist=[(a.gt(0), a),  # condition, replacement
...                       (b.gt(0), b)])
0    6
1    3
2    1
3    2
Name: c, dtype: int64