Python

NumPy np.count_nonzero

In this article, we will explore the NumPy count_nonzero() function and its syntax and provide examples of how to use it.

The count_nonzero() function allows you to determine the number of non-zero values in a given array.

Let us discuss.

Function Syntax

The count_nonzero() function can be expressed as shown below:

numpy.count_nonzero(a, axis=None, *, keepdims=False)

Parameters

The function parameters are as follows:

1. a – refers to the input array to count the non-zero values.
2. axis – specifies along which axis to count the non-zero values.

Return Value

The function then returns the number of non-zero values in the array along the specified axis.

Note: if the axis is set to None, the function will flatten the array and return the total number of non-zero values in the entire array.

Example #1

Consider the example code provided below:

# import numpy
import numpy as np
arr = np.array([0,1,2,3,0,4,5,0,6,7,8,9])
print(f"total elements: {arr.size}")
print(f"total non-zero: {np.count_nonzero(arr)}")

In the example code above, we have a one-dimensional array containing three zero values.

We then use the arr.size property to get the total number of elements in the array and the count_nonzero() function to get the number of non-zero elements.

The code above should return:

total elements: 12
total non-zero: 9

Example #2

The example below shows the count_nonzero() function with a 2D array along the zero axis.

arr_2d = np.array([[0,1,2,3], [0,4,5,6],[0,7,8,9]])
print(f"total elements: {arr_2d.size}")
print(f"total non-zero: {np.count_nonzero(arr_2d, axis=0)}")

In this case, we have a 2D array with three zero elements. The function should determine the number of non-zero values along the zero axis and return the output as shown below:

total elements: 12
total non-zero: [0 3 3 3]

Example #3

The same operation can be said along the one axis. An example illustration is as shown in the code below:

arr_2d = np.array([[0,1,2,3], [0,4,5,6],[0,7,8,9]])
print(f"total elements: {arr_2d.size}")
print(f"total non-zero: {np.count_nonzero(arr_2d, axis=1)}")

The above code should return:

total elements: 12
total non-zero: [3 3 3]

Termination

With the help of this guide, you are now familiar with the NumPy count_nonzero() function and how to use it in your NumPy arrays.