Python中numpy的np.where()函数

numpy.where() 有两种用法:

1. np.where(condition, x, y)
满足条件(condition),输出x,不满足输出y。

import numpy as np
a = np.arange(10)
print(a)
aa = np.where(a, 1, -1)
print(aa)
aaa = np.where(a > 5, 1, -1)
print(aaa)

[0 1 2 3 4 5 6 7 8 9]
[-1  1  1  1  1  1  1  1  1  1]
[-1 -1 -1 -1 -1 -1  1  1  1  1]
np.where([[True,False], [True,True]],    # 官网上的例子
             [[1,2], [3,4]],
             [[9,8], [7,6]])

array([[1, 8],
       [3, 4]])
``
`
上面这个例子的条件为[[True,False], [True,False]],分别对应最后输出结果的四个值。第一个值从[1,9]中选,因为条件为True,所以是选1。第二个值从[2,8]中选,因为条件为False,所以选8,后面的以此类推。

同理,再看下面的一个例子:

```python
a = 10
np.where([[a > 5,a < 5], [a == 10,a == 7]],
             [["chosen","not chosen"], ["chosen","not chosen"]],
             [["not chosen","chosen"], ["not chosen","chosen"]])

array([['chosen', 'chosen'],
       ['chosen', 'chosen']], dtype='<U10')

2. np.where(condition)
只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 。这里的坐标以tuple的形式给出,通常原数组有多少维,输出的tuple中就包含几个数组,分别对应符合条件元素的各维坐标。

一维的情况:

a = np.array([2, 4, 6, 8, 10])
print(np.where(a > 5))
print(type(np.where(a > 5)))
print(a[np.where(a > 5)])
print(type(a[np.where(a > 5)]))

(array([2, 3, 4], dtype=int64),)
<class 'tuple'>
[ 6  8 10]
<class 'numpy.ndarray'>

二维的情况:

a = np.arange(27).reshape(3,3,3)
a

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

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

np.where(a > 5)

(array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2],
       dtype=int64),
 array([2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2],
       dtype=int64),
 array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2],
       dtype=int64))

a[np.where(a > 5)]
array([ 6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
       23, 24, 25, 26])

所以满足条件的坐标为(0, 2, 0), (0, 2, 1)…

所以np.where会输出每个元素的对应的坐标,因为原数组有三维,所以tuple中有三个数组。

  • 47
    点赞
  • 222
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值