NumPy - nonzero() function
The NumPy nonzero() function returns the indices of the elements that are non-zero. Returned value is a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always tested and returned in row-major, C-style order.
Syntax
numpy.nonzero(a)
Parameters
a |
Required. Specify the input array (array_like). |
Return Value
Returns the indices of elements that are non-zero.
Example:
In the example below, nonzero() function is used to find out index of all elements which are non-zero.
import numpy as np Arr = np.array([10, 20, 0, 0, 50, 0, 70]) print("Array is:") print(Arr) #index of all elements which are non-zero x = np.nonzero(Arr) print("\nIndices of nonzero elements:") print(x) #displaying all nonzero elements print("\nAll nonzero elements:") print(Arr[x])
The output of the above code will be:
Array is: [10 20 0 0 50 0 70] Indices of nonzero elements: (array([0, 1, 4, 6]),) All nonzero elements: [10 20 50 70]
Example:
Similarly, nonzero elements from a 2-D array can be found out using nonzero() function.
import numpy as np Arr = np.array([[1, 2, 0], [0, 5, 0], [7, 0, 9]]) print("Array is:") print(Arr) #index of all elements which are non-zero x = np.nonzero(Arr) print("\nIndices of nonzero elements:") print(x) #displaying all nonzero elements print("\nAll nonzero elements:") print(Arr[x])
The output of the above code will be:
Array is: [[1 2 0] [0 5 0] [7 0 9]] Indices of nonzero elements: (array([0, 0, 1, 2, 2]), array([0, 1, 1, 0, 2])) All nonzero elements: [1 2 5 7 9]
Example:
A condition can be applied to nonzero() function as shown in the example below.
import numpy as np Arr = np.array([90, 80, 10, 20, 50]) print("Array is:") print(Arr) #index of all elements which are greater than 25 x = np.nonzero(Arr > 25) print("\nIndices of elements greater than 25:") print(x) #displaying all elements greater than 25 print("\nAll elements greater than 25:") print(Arr[x])
The output of the above code will be:
Array is: [90 80 10 20 50] Indices of elements greater than 25: (array([0, 1, 4]),) All elements greater than 25: [90 80 50]
❮ NumPy - Functions