在 NumPy 数组中查找等于零的元素的索引
有时我们需要找出数组中所有空元素的索引。 Numpy 提供了许多函数来计算所有空元素的索引。
方法 1:使用查找空元素的索引 numpy.where()
此函数返回输入数组中满足给定条件的元素的索引。
句法 :
numpy.where(condition[, x, y])
When True, yield x, otherwise yield y
Python3
# importing Numpy package
import numpy as np
# creating a 1-D Numpy array
n_array = np.array([1, 0, 2, 0, 3, 0, 0, 5,
6, 7, 5, 0, 8])
print("Original array:")
print(n_array)
# finding indices of null elements using np.where()
print("\nIndices of elements equal to zero of the \
given 1-D array:")
res = np.where(n_array == 0)[0]
print(res)
Python3
# importing Numpy package
import numpy as np
# creating a 3-D Numpy array
n_array = np.array([[0, 2, 3],
[4, 1, 0],
[0, 0, 2]])
print("Original array:")
print(n_array)
# finding indices of null elements
# using np.argwhere()
print("\nIndices of null elements:")
res = np.argwhere(n_array == 0)
print(res)
Python3
# importing Numpy package
import numpy as np
# creating a 1-D Numpy array
n_array = np.array([1, 10, 2, 0, 3, 9, 0,
5, 0, 7, 5, 0, 0])
print("Original array:")
print(n_array)
# finding indices of null elements using
# np.nonzero()
print("\nIndices of null elements:")
res = np.nonzero(n_array == 0)
print(res)
输出:
方法 2:使用numpy.argwhere()查找空元素的索引
此函数用于查找按元素分组的非零数组元素的索引。
语法:
numpy.argwhere(arr)
Python3
# importing Numpy package
import numpy as np
# creating a 3-D Numpy array
n_array = np.array([[0, 2, 3],
[4, 1, 0],
[0, 0, 2]])
print("Original array:")
print(n_array)
# finding indices of null elements
# using np.argwhere()
print("\nIndices of null elements:")
res = np.argwhere(n_array == 0)
print(res)
输出:
方法 3:使用numpy.nonzero()查找空元素的索引
此函数用于计算非零元素的索引。它返回一个数组元组,arr 的每个维度一个,包含该维度中非零元素的索引。
句法:
numpy.nonzero(arr)
Python3
# importing Numpy package
import numpy as np
# creating a 1-D Numpy array
n_array = np.array([1, 10, 2, 0, 3, 9, 0,
5, 0, 7, 5, 0, 0])
print("Original array:")
print(n_array)
# finding indices of null elements using
# np.nonzero()
print("\nIndices of null elements:")
res = np.nonzero(n_array == 0)
print(res)
输出: