python numpy.where()函数的用法

numpy.where(condition[,x,y])

返回元素,可以是x或y,具体取决于条件(condition)

如果只给出条件,则返回condition.nonzero()

对于不同的输入,where返回的值是不同的。

参数:ccondition:array_llike,bool
 如果为True,则产生x,否则产生y。
 x,y:array_like,可选
 要从中选择的值。x,y和条件需要可以播放到某种形状。
返回值:

out:ndarray或ndarray元组

 如果同时指定了x和y,则输出数组包含x的元素,其中condition为True,其他元素来自y。如果只给出条件,则返回元组condition.nanzero(),条件为True的索引。

 

Example:

 当数组是一维数组时,返回的值是一维的索引,所以只有一组索引数组

a = np.arange(8)

a
array([0, 1, 2, 3, 4, 5, 6, 7])

np.where(a>4)
(array([5, 6, 7], dtype=int64),)

当数组是二维数组时,满足条件的数组值返回的是值的位置索引,因此会有两组索引数组来表示值的位置,返回的第一个array表示行坐标,第二个array表示纵坐标,两者一一对应

b = np.arange(4*5).reshape(4,5)

b
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

np.where(b>14)
(array([3, 3, 3, 3, 3], dtype=int64), array([0, 1, 2, 3, 4], dtype=int64))

当条件(condition)为多维数组时,根据条件中为True则选择x中相应的数值,为False选择y中相应的数值

np.where([[False, True], [False, True]],
        [[5, 3], [7, 9]],
        [[2, 6], [1, 8]])
 
array([[2, 3],[1, 9]])

第一个元素中的第一个值为False,所以选择y中的2,第二个值为True,选择x中3,第二个元素中的第一个值为False,所以选择y中的1,第二个值为True,选择x中9.

当参数中只给出条件时,则返回非零元素的索引:

np.where([[0, 1], [1, 1]])
(array([0, 1, 1], dtype=int64), array([1, 0, 1], dtype=int64))
x = np.arange(12.).reshape(4, 3)

x
array([[  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,   8.],
       [  9.,  10.,  11.]])

np.where(x>7)
(array([2, 3, 3, 3], dtype=int64), array([2, 0, 1, 2], dtype=int64))

x[np.where( x > 6.0 )]           
array([  7.,   8.,   9.,  10.,  11.])

np.where(x < 8, x, np.nan) 
array([[  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,  nan],
       [ nan,  nan,  nan]])

根据找到的元素的索引找到元素的具体位置

x = np.arange(12.).reshape(4, 3)

x
array([[  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,   8.],
       [  9.,  10.,  11.]])

positions = [2,6,10]

ins = np.isin(x,positions)

ins
array([[False, False,  True],
       [False, False, False],
       [ True, False, False],
       [False,  True, False]], dtype=bool)

np.where(ins)
(array([0, 2, 3], dtype=int64), array([2, 0, 1], dtype=int64))

 

 

 

 

 

 

  • 102
    点赞
  • 343
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值