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.
numpy.nonzero(a)
The nonzero()
function takes a single and mandatory parameter a
, which represents the input array.
The nonzero()
function returns the indices of the elements that are non-zero.
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)
numpy
module.myarray1
, using the array()
function.nonzero()
function on the variable myarray1
. The result is assigned to another variable, myarray
.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.