无涯教程-DataFrame.where函数

45 阅读1分钟

where()方法的主要任务是检查数据框是否存在一个或多个条件,并相应地返回结果。默认情况下,如果行不满足条件,则将其填充为 NaN 值。

语法

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

参数

  • cond       -   它指的是一种或多种条件来检查数据帧。
  • other      -   它用用户定义的对象替换不满足条件的行。默认值为NaN。
  • inplace   -  返回值布尔值。如果该值为true,则会在dataframe中进行更改。
  • axis          -  要检查的轴(行或列)。

例1

import pandas as pd
import numpy as np
a = pd.Series(range(5))
a.where(a > 0)
a.mask(a > 0) 
a.where(a > 1, 10)
info = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=[A, B])
info
b = info % 3 == 0
info.where(b, -info)
info.where(b, -info) == np.where(b, info, -info)
info.where(b, -info) == info.mask(~b, -info)

输出

     A        B
0   True     True
1   True     True
2   True     True
3   True     True
4   True     True

参考链接

www.learnfk.com/pandas/pand…