什么是Python中的Numpy argwhere()函数?

1,956 阅读2分钟

Numpy argwhere()函数找到按元素分组的非零数组元素的索引。np.argwhere()与np.transpose(np.nonzero())相同。argwhere()函数的输出不适合用于数组的索引。为此,请使用nonzero(a)代替。

np.argwhere

np.argwhere()是一个numpy库的方法,用于查找按元素分组的非零数组项目的索引。argwhere()函数接收一个类似数组的参数,并返回数组元素的索引。

语法

numpy.argwhere(a)

参数

np argwhere()函数接收一个参数a,其数据类型为array_like。

例子

首先,我们将导入numpy库,然后定义数据。

然后我们将使用np argwhere()函数来查找非零元素的索引:

# app.py

import numpy as np

data = [[ 11, 0, 21], [0, 19, 18]]
print(data)
nonZeroIndices = np.argwhere(data)
print(nonZeroIndices)

输出

python3 app.py
[[11, 0, 21], [0, 19, 18]]
[[0 0]
 [0 2]
 [1 1]
 [1 2]]

在上面的代码中,11不是零,它的索引是[0, 0],意味着在0行和0列有11个元素。所以它返回[0 ,0]。同样,21号元素的索引是[0, 2]。

19也是一样,它的索引是[1, 1],因为不是行是1,而且在那一行,列也是1,这就是为什么它返回[1, 1],18也一样,它的索引是[1, 2]。

将条件应用于np argwhere()函数

将逻辑条件传递给np argwhere()函数,得到满足条件的指定元素的索引。

比方说,我们只想要大于4的元素的索引。

请看下面的代码:

# app.py

import numpy as np

data = np.arange(8).reshape(2, 4)
print(data)
nonZeroIndices = np.argwhere(data > 4)
print('The indices of the elements that are > 4')
print(nonZeroIndices)

输出

python3 app.py
[[0 1 2 3]
 [4 5 6 7]]
The indices of the elements that are > 4
[[1 1]
 [1 2]
 [1 3]]

我们在上面的代码中使用了np arange()函数来创建一个(2, 4)数组。

我们只打印大于4的元素的索引。

数据数组中,你可以看到0行没有值大于4的元素,所以在输出中,没有0行。

让我们看看另一个条件,在此基础上,我们将得到索引:

# app.py

import numpy as np

data = np.arange(8).reshape(2, 4)
print(data)
nonZeroIndices = np.argwhere(data != 3)
print('The indices of the elements that are > 4')
print(nonZeroIndices)

输出

python3 app.py
[[0 1 2 3]
 [4 5 6 7]]
The indices of the elements that are > 4
[[0 0]
 [0 1]
 [0 2]
 [1 0]
 [1 1]
 [1 2]
 [1 3]]

在上面的例子中,我们只得到元素值不为3的索引。否则,每个索引都会被打印出来,即使是0值的元素,np.argwhere()函数就介绍到这里。