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 array
myarray1 = np.array([1, 0, 3, 0, 0, 4, 5, 0, 8])
# calling the nonzero() function
myarray = np.nonzero(myarray1)
print(myarray)

Code explanation

  • Line 1: We import the numpy module.
  • Line 3: We create a 1-D array, myarray1, using the array() function.
  • Line 6: We implement the nonzero() function on the variable myarray1. 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 of 0. This is followed by the third element of the array which has an index number of 2, and so on and so forth.

Free Resources