7. np.where, np.argwhere, df.where, df.mask

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差不多,只是条件相反。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值