NumPy nonzero()

The NumPy nonzero() method finds the indices of array elements that are not zero.

Example

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() 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

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)

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

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)

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.

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)

Output

(array([1, 3, 5]),)

Note: To group the indices by the element, rather than dimension, we use argwhere().