pandas.Series.mask#

Series.mask(cond, other=_NoDefault.no_default, *, inplace=False, axis=None, level=None)[源代码]#

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

Parameters:
condbool Series/DataFrame, 类数组对象, 或可调用对象

cond 为 False 的地方,保留原始值。在 cond 为 True 的地方,用 other 中的相应值替换。如果 cond 是可调用对象,它将在 Series/DataFrame 上计算,并应返回布尔 Series/DataFrame 或数组。该可调用对象不得更改输入 Series/DataFrame(尽管 pandas 不会检查它)。

other标量、Series/DataFrame 或可调用对象

其中 cond 为 True 的条目将被 other 中的相应值替换。如果 other 是可调用对象,它将在 Series/DataFrame 上计算,并应返回标量或 Series/DataFrame。该可调用对象不得更改输入 Series/DataFrame(尽管 pandas 不会检查它)。如果未指定,则条目将用相应的 NULL 值填充(对于 numpy dtypes 为 np.nan,对于扩展 dtypes 为 pd.NA)。

inplacebool,默认 False

是否在数据上原地执行操作。

axisint,默认 None

如果需要,将对齐轴。对于 Series,此参数未使用,默认为 0。

levelint,默认 None

如果需要,将对齐级别。

Returns:
与调用者相同类型,如果 inplace=True 则为 None。

参见

DataFrame.where()

返回与 self 形状相同的对象。

Notes

mask 方法是 if-then 模式的应用。对于调用 DataFrame 中的每个元素,如果 condFalse,则使用该元素;否则,使用来自 DataFrame other 的相应元素。如果 other 的轴与 cond Series/DataFrame 的轴不对齐,则具有错误对齐索引位置的元素将被填充为 True。

DataFrame.where() 的签名与 numpy.where() 不同。大致上 df1.where(m, df2) 等同于 np.where(m, df1, df2)

有关更多详细信息和示例,请参阅 indexing 中的 mask 文档。

对象的 dtype 优先。填充值将被强制转换为对象的 dtype,如果可以无损转换的话。

Examples

>>> s = pd.Series(range(5))
>>> s.where(s > 0)
0    NaN
1    1.0
2    2.0
3    3.0
4    4.0
dtype: float64
>>> s.mask(s > 0)
0    0.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64
>>> s = pd.Series(range(5))
>>> t = pd.Series([True, False])
>>> s.where(t, 99)
0     0
1    99
2    99
3    99
4    99
dtype: int64
>>> s.mask(t, 99)
0    99
1     1
2    99
3    99
4    99
dtype: int64
>>> s.where(s > 1, 10)
0    10
1    10
2    2
3    3
4    4
dtype: int64
>>> s.mask(s > 1, 10)
0     0
1     1
2    10
3    10
4    10
dtype: int64
>>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
>>> df
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9
>>> m = df % 3 == 0
>>> df.where(m, -df)
   A  B
0  0 -1
1 -2  3
2 -4 -5
3  6 -7
4 -8  9
>>> df.where(m, -df) == np.where(m, df, -df)
      A     B
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True
>>> df.where(m, -df) == df.mask(~m, -df)
      A     B
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True