![]() |
VOOZH | about |
It means you want to find the positions (row and column indices) where the elements of a NumPy array are equal to zero. For example, Given the array [[1, 0, 3], [0, 5, 6], [7, 8, 0]], find the row and column indices of all elements equal to zero.
The numpy.nonzero() function returns the indices of non-zero elements. By applying a condition, we can use it to find positions of zeros.
Example: In this example, we create a 1-D array and use np.nonzero() to locate zero values.
Array: [ 1 10 2 0 3 9 0 5 0 7 5 0 0] Indices of zero elements: (array([ 3, 6, 8, 11, 12]),)
Explanation
The numpy.where() function returns indices where a condition holds true. It’s one of the most common ways to locate elements.
Example: Here, we use np.where() to find the indices of zeros in a 1-D array.
Array: [1 0 2 0 3 0 0 5 6 7 5 0 8] Indices of zero elements: [ 1 3 5 6 11]
Explanation:
The numpy.argwhere() function returns the indices of elements that satisfy a condition, grouped by row/column in multi-dimensional arrays.
Example: In this example, we use a 2-D array and find all zero indices using np.argwhere().
Array: [[0 2 3] [4 1 0] [0 0 2]] Indices of zero elements: [[0 0] [1 2] [2 0] [2 1]]
Explanation
The numpy.extract() function returns elements that satisfy a condition. By combining it with np.arange(), we can extract the indices of zeros.
Example: Here, we use np.extract() to directly get the indices of zeros in a 1-D array.
Array: [1 0 2 0 3 0 0 5 6 7 5 0 8] Indices of zero elements: [ 1 3 5 6 11]
Explanation: