maxframe.dataframe.DataFrame.where#

DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False)#

替换条件为 False 的值。

参数:
  • cond (bool Series/DataFrame, array-like, or callable) -- 在 cond 为 False 的位置保留原始值。在 True 的位置,使用 other 中对应的值进行替换。如果 cond 是可调用对象,则会在 Series/DataFrame 上计算,并应返回布尔型 Series/DataFrame 或数组。该可调用对象不得更改输入的 Series/DataFrame(尽管 pandas 不会检查这一点)。

  • other (scalar, Series/DataFrame, or callable) -- cond 为 True 的条目将被 other 中的对应值替换。如果 other 是可调用对象,则会在 Series/DataFrame 上计算,并应返回标量或 Series/DataFrame。该可调用对象不得更改输入的 Series/DataFrame(尽管 pandas 不会检查这一点)。

  • inplace (bool, default False) -- 是否就地修改数据。

  • axis (int, default None) -- 如果需要对齐的轴。

  • level (int, default None) -- 如果需要对齐的层级。

返回类型:

Same type as caller

参见

DataFrame.mask()

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

备注

mask 方法是 if-then 惯用法的一种应用。对于调用 DataFrame 中的每个元素,如果 condFalse 则使用该元素;否则使用 DataFrame other 中对应的元素。

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

更多详情和示例请参见 indexing 中的 mask 文档。

示例

>>> import maxframe.tensor as mt
>>> import maxframe.dataframe as md
>>> s = md.Series(range(5))
>>> s.where(s > 0).execute()
0    NaN
1    1.0
2    2.0
3    3.0
4    4.0
dtype: float64
>>> s.mask(s > 0).execute()
0    0.0
1    NaN
2    NaN
3    NaN
4    NaN
dtype: float64
>>> s.where(s > 1, 10).execute()
0    10
1    10
2    2
3    3
4    4
dtype: int64
>>> df = md.DataFrame(mt.arange(10).reshape(-1, 2), columns=['A', 'B'])
>>> df.execute()
   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).execute()
   A  B
0  0 -1
1 -2  3
2 -4 -5
3  6 -7
4 -8  9
>>> df.where(m, -df) == mt.where(m, df, -df).execute()
      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).execute()
      A     B
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True