pandas.DataFrame.mask #

数据框。mask ( cond , other = _NoDefault.no_default , * , inplace = False , axis = None , level = None ) [来源] #

替换条件为 True 的值。

参数
cond bool Series/DataFrame,类似数组或可调用

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

其他标量、系列/数据帧或可调用

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

inplace布尔值,默认 False

是否对数据执行就地操作。

axis int,默认无

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

level int,默认无

如果需要的话,调整水平。

返回
与调用者类型相同或 None if inplace=True

也可以看看

DataFrame.where()

返回一个与自身形状相同的对象。

笔记

mask 方法是 if-then 习惯用法的应用。对于调用 DataFrame 中的每个元素,如果cond是则False使用该元素;否则other使用DataFrame 中的相应元素 。如果 的轴other与 Series/DataFrame 的轴不对齐 cond,则未对齐的索引位置将用 True 填充。

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

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

对象的数据类型优先。如果可以无损地完成此操作,则填充值将转换为对象的数据类型。

例子

>>> 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