pandas.DataFrame.mask#

DataFrame.mask(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=NoDefault.no_default)[源代码]#

替换条件为True的值。

参数
condBool系列/DataFrame、类似数组或可调用

哪里 cond 为False,则保留原始值。如果为True,则替换为 other 。如果 cond 是可调用的,则它是在Series/DataFrame上计算的,应该返回布尔Series/DataFrame或数组。Callable不能更改输入Series/DataFrame(尽管Pandas不检查它)。

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

条目,其中 cond 如果为True,则替换为 other 。如果Other是可调用的,则它是在Series/DataFrame上计算的,应该返回标量或Series/DataFrame。Callable不能更改输入Series/DataFrame(尽管Pandas不检查它)。

inplace布尔值,默认为False

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

axisInt,默认为无

如果需要,对齐轴。

levelInt,默认为无

对齐级别(如果需要)。

errors字符串,{‘RAISE’,‘IGNORE’},默认‘RAISE’

请注意,目前该参数不会影响结果,并且将始终强制转换为合适的dtype。

  • ‘Raise’:允许引发异常。

  • ‘Ignore’:取消异常。出错时返回原始对象。

try_cast布尔默认为无

尝试将结果转换回输入类型(如果可能)。

1.3.0 版后已移除: 如有必要,请手动回放。

退货
与调用者相同的类型或无(如果 inplace=True

参见

DataFrame.where()

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

注意事项

掩码方法是If-Then习惯用法的应用。对于调用DataFrame中的每个元素,如果 condFalse 则使用元素;否则使用DataFrame中的相应元素 other 是使用的。

的签名 DataFrame.where() 不同于 numpy.where() 。粗略地说 df1.where(m, df2) 相当于 np.where(m, df1, df2)

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

示例

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