The NumPy nonzero() method finds the indices of array elements that are not zero.
nonzero() Syntax
The syntax of nonzero() is:
numpy.nonzero(array)
nonzero() Argument
The nonzero() method takes one argument:
array- an array whose non-zero indices are to be found
nonzero() Return Value
The nonzero() method returns a tuple of arrays; one for each dimension of the input array, containing the indices of the non-zero elements in that dimension.
Example 1: numpy.nonzero() With Arrays
Output
Indices of non-zero elements in numberArray: (array([0, 3, 4]),) Indices of non-empty elements in stringArray: (array([0, 1, 3]),)
Example 2: numpy.nonzero() With 2-D Arrays
Output
(array([0, 0, 1, 2, 2]), array([0, 2, 0, 1, 2]))
Here, the output of the code is a tuple containing two arrays.
The first array [0, 0, 1, 2, 2] represents the row indices of the non-zero elements, and the second array [0, 2, 0, 1, 2] represents the corresponding column indices.
- The first non-zero element is 1, which is located at row index 0 and column index 0.
- The second non-zero element is 3, which is located at row index 0 and column index 2, and so on.
Example 3: numpy.nonzero() With Condition
We can also use nonzero() to find the indices of elements that satisfy the given condition.
Output
(array([1, 3, 5]),)
Note: To group the indices by the element, rather than dimension, we use argwhere().