DataFrame.where - 按条件替换数据帧成员
DataFrame的where方法按条件替换数据帧中的成员值。 当条件满足时保留数据帧中的值。
方法原型
DataFrame.where(self, cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False)
参数:
- cond:布尔、序列、数据帧、数组或callable函数,表示 要检测的条件。当条件满足时保留原始值,否则进行替换
- other:条件不满足时的替换值。
- inplace:布尔,默认值:False。是否执行就地操作
- axis:int,默认值:None,需要时是否对齐轴
- level:int,默认值:None,需要时是否对齐层级
- errors:字符串,raise或ignore,默认值:raise
- try_cast:布尔,默认值:False,是否尝试将结果强制转换为输入类型
返回值:返回数据帧对象
示例代码
下面的代码创建一个5x1的数据帧,并将小于1的值替换为 NaN:
>>> 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
下面的代码使用ndarray创建一个数据帧,并将不能整除3的 成员替换为其相反数:
>>> 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