7. np.where, np.argwhere, df.where, df.mask
7.1 np.where
numpy.where(condition[, x, y])
根据条件选择x或y的元素返回。如果condition为真,返回x的元素;反之返回y的元素
a = np.arange(10)
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.where(a < 5, a, 10*a)
array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
7.2 np.argwhere
numpy.argwhere(a)
返回a中非零元素的索引。可以结合逻辑表达式使用,寻找数组中合乎条件的位置。
x = np.arange(6).reshape(2,3)
x
array([[0, 1, 2],
[3, 4, 5]])
np.argwhere(x>1)
array([[0, 2],
[1, 0],
[1, 1],
[1, 2]])
7.3 df.where
DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False)
条件为False
时,替换为other对应的值。other可以是常量,也可以是可调用对象,此时other的形状要和df形状一致。
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
7.4 df.mask
与df.where差不多,只是条件相反。