Understand numpy.nonzero() with Examples – NumPy Tutorial

By | November 18, 2022

numpy.nonzero() function can return the indices of the elements that are non-zero in a numpy ndarray. In this tutorial, we will use some examples to help you understand how to use it.

Syntax

numpy.nonzero() is defined as:

numpy.nonzero(a)

Here a is an array. This function will return a tuple, which contains two elements.

How to use numpy.nonzero()?

We will use some examples to show you how to use.

For example:

import numpy as np

x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
print(x)

y = np.nonzero(x)
print(len(y))
print(y)

Run this code, we will see:

[[3 0 0]
 [0 4 0]
 [5 6 0]]
2
(array([0, 1, 2, 2], dtype=int64), array([0, 1, 0, 1], dtype=int64))

We can find:

  • y is a tuple, it contains two elements
  • y[0] = array([0, 1, 2, 2], dtype=int64), y[1] = array([0, 1, 0, 1], dtype=int64)

Why y[0] = array([0, 1, 2, 2], dtype=int64) and y[1] = array([0, 1, 0, 1], dtype=int64)?

As to this example, x is:

[[3 0 0]
 [0 4 0]
 [5 6 0]]

y[0] contains the axis that contains non-zero, it can be determined as follows:

Understand numpy.nonzero() example 1

There are a non-zero element on axis = 0 and axis = 1, two non-zero elements on axis = 2

So y[0] = [0, 1, 2, 2]

We also can find the size of y[0] is equal to the number of non-zero elements.

y[1] contains the indices of non-zero elements on each axis.

As to example above, we can find:

  • the indice of 3 is 0 on axis = 0
  • the indice of 4 is 1 on axis = 1
  • the indices of 5 and 6 are 0, 1 on axis = 2

It is:

Understand numpy.nonzero() example 2

So y[1] = [0, 1, 0, 1]

Look at this example below:

import numpy as np

x = np.array([[1, 0, 3], [4, 0, 6], [7, 8, 9]])
print(x)

y = np.nonzero(x)

We can find y is:

(array([0, 0, 1, 1, 2, 2, 2], dtype=int64), array([0, 2, 0, 2, 0, 1, 2], dtype=int64))

We also can use numpy.nonzero() on boolean data.

For example:

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
x = a > 3
# x will be
array([[False, False, False],
       [ True,  True,  True],
       [ True,  True,  True]])
y = np.nonzero(a > 3)
#y will be
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))

Leave a Reply