NumPy 的 nonzero()
方法查找数组中非零元素的索引。
示例
import numpy as np
originalArray = np.array([1, 0, 0, 4, -5])
# return the indices of elements that are not zero
result = np.nonzero(originalArray)
print(result)
# Output: (array([0, 3, 4]),)
nonzero() 语法
nonzero()
的语法是:
numpy.nonzero(array)
nonzero() 参数
nonzero()
方法接受一个参数:
array
- 要查找非零索引的数组
nonzero() 返回值
nonzero()
方法返回一个 tuple
,其中包含的数组数量等于输入数组的维度数,每个数组包含该维度中非零元素的索引。
示例 1:numpy.nonzero() 与数组
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
numberResult = np.nonzero(numberArray)
# return indices of non-empty elements in stringArray
stringResult = np.nonzero(stringArray)
print('Indices of non-zero elements in numberArray:', numberResult)
print('Indices of non-empty elements in stringArray:', stringResult)
输出
Indices of non-zero elements in numberArray: (array([0, 3, 4]),) Indices of non-empty elements in stringArray: (array([0, 1, 3]),)
示例 2:numpy.nonzero() 与二维数组
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.nonzero(array)
print(result)
输出
(array([0, 0, 1, 2, 2]), array([0, 2, 0, 1, 2]))
在这里,代码的输出是一个包含两个数组的元组。
第一个数组 [0, 0, 1, 2, 2] 表示非零元素的行索引,第二个数组 [0, 2, 0, 1, 2] 表示相应的列索引。
- 第一个非零元素是 1,位于行索引 0 和列索引 0。
- 第二个非零元素是 3,位于行索引 0 和列索引 2,依此类推。
示例 3:numpy.nonzero() 与条件
我们也可以使用 nonzero()
来查找满足给定条件的元素的索引。
import numpy as np
array = np.array([1, 2, 3, 4, 5, 6])
# return indices of elements that satisfy the condition
# true if the array element is even
result = np.nonzero(array%2==0)
print(result)
输出
(array([1, 3, 5]),)
注意: 要按元素而非维度对索引进行分组,请使用 argwhere()。