使用numpy.argwhere在np.array中获取匹配值
在本文中,我们将介绍如何使用numpy.argwhere功能来获取一个np.array中与一个特定值匹配的所有索引。
阅读更多:Numpy 教程
numpy.argwhere简介
numpy.argwhere函数返回一个数组中非零元素的索引。np.argwhere(a)与np.transpose(np.nonzero(a))作用相同。
这是一个使用numpy.argwhere功能的例子:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
listOfCoordinates = np.argwhere(a == 5)
print(listOfCoordinates)
这将打印出:
[[1 1]]
这个例子中,我们定义了一个有三个行和三个列的np.array,并在第二行第二列加入了一个数值为5的元素。使用numpy.argwhere,我们得到了该元素的索引。
使用numpy.argwhere获取一组匹配值的索引
我们也可以使用numpy.argwhere获取一组匹配值的索引。
如下所示:
import numpy as np
a = np.array([1, 2, 3, 2, 4, 2])
listOfCoordinates = np.argwhere(a == 2)
print(listOfCoordinates)
这将打印出:
[[1]
[3]
[5]]
在这个例子中,我们定义了一个一维数组,然后使用numpy.argwhere获取与值为2匹配的所有索引。
使用numpy.argwhere获取匹配值的索引与np.where相比有何不同?
numpy.argwhere函数返回匹配值的索引。但是,np.where函数返回值为True的索引。
假设我们有以下的np.array:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
listOfCoordinates = np.where(a > 5)
print(listOfCoordinates)
这将打印出:
(array([1, 2, 2, 2]), array([2, 0, 1, 2]))
这个例子中,我们找到了一个有三个行和三个列的np.array中所有值大于5的元素。
请注意,我们得到的是一个元组,元组中有两个数组。第一个数组包含行号,第二个数组包含列号。因此,我们可以使用以下代码来获取相应索引:
rows, columns = np.where(a > 5)
for r, c in zip(rows, columns):
print(f"The value at ({r}, {c}) is {a[r][c]}")
这将打印出:
The value at (1, 2) is 6
The value at (2, 0) is 7
The value at (2, 1) is 8
The value at (2, 2) is 9
总结
使用numpy.argwhere可以轻松地从一个np.array中获取所有与特定值匹配的索引,无论是与一个值匹配还是与一组值匹配。与np.where函数相比,numpy.argwhere的返回值更加易于使用,因为它返回一个包含所有匹配值索引的数组。
极客教程