What is the numpy.nonzero() function from NumPy in Python?
Overview
The nonzero() function in Python is used to return the indices (the index numbers or index positions) of the elements of an array that are non-zero.
Syntax
numpy.nonzero(a)
Parameter value
The nonzero() function takes a single and mandatory parameter a, which represents the input array.
Return value
The nonzero() function returns the indices of the elements that are non-zero.
Code example
import numpy as np# creating an input arraymyarray1 = np.array([1, 0, 3, 0, 0, 4, 5, 0, 8])# calling the nonzero() functionmyarray = np.nonzero(myarray1)print(myarray)
Code explanation
- Line 1: We import the
numpymodule. - Line 3: We create a 1-D array,
myarray1, using thearray()function. - Line 6: We implement the
nonzero()function on the variablemyarray1. The result is assigned to another variable,myarray. - Line 8: We print the variable
myarray.
It is worth noting from the output of the code
(array([0, 2, 5, 6, 8]),)that the first non-zero element in the input array is the first element of the array which has an index number of0. This is followed by the third element of the array which has an index number of2, and so on and so forth.