NumPy 的 argwhere()
方法查找数组中非零元素的索引,并将其作为二维数组返回。
示例
import numpy as np
originalArray = np.array([1, 0, 0, 4, -5])
# return the indices of elements that are not zero as a 2D array
result = np.argwhere(originalArray )
print(result)
'''
Output:
[[0]
[3]
[4]]
'''
argwhere() 语法
argwhere()
的语法是:
numpy.argwhere(array)
argwhere() 参数
argwhere()
方法接受一个参数:
array
- 要查找非零索引的数组
argwhere() 返回值
argwhere()
方法返回非零元素的索引,形式为一个二维数组。
示例 1:numpy.argwhere() 与数组
import numpy as np
numberArray = np.array([1, 0, 0, 4, -5])
stringArray = np.array(['Apple', 'Ball', '', 'Dog'])
# return indices of non-zero elements in numberArray as a 2D array
numberResult = np.argwhere(numberArray)
# return indices of non-empty elements in stringArray as a 2D array
stringResult = np.argwhere(stringArray)
print('Array of non-empty indices in numberArray:\n', numberResult)
print('\nArray of non-empty indices in stringArray:\n', stringResult)
输出
Array of non-empty indices in numberArray: [[0] [3] [4]] Array of non-empty indices in stringArray: [[0] [1] [3]]
示例 2:numpy.argwhere() 与二维数组
import numpy as np
array = np.array([[1, 0, 3],
[2, 0, 0],
[0, 4, 5]])
# return indices of elements that are not zero
result = np.argwhere(array)
print(result)
输出
[[0 0] [0 2] [1 0] [2 1] [2 2]]
在这里,输出以行-列格式表示非零元素的位置。
第一个非零元素是 1,在行-列格式中的索引是 [0, 0]。类似地,第二个非零元素是 3,在行-列格式中的索引是 [0, 2],依此类推。
示例 3:numpy.argwhere() 与条件
我们还可以使用 argwhere()
来查找满足给定条件的元素的索引。
import numpy as np
array = np.array([1, 2, 3, 4, 5, 6])
# check array elements for odd/even condition
# return true if the array element is even
result = np.argwhere(array%2==0)
print(result)
输出
[[1] [3] [5]]
注意:要按维度(而不是按元素)对索引进行分组,可以使用 nonzero()
。