VOOZH about

URL: https://www.geeksforgeeks.org/python/numpy-count_nonzero-method-python/

⇱ Numpy count_nonzero method - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Numpy count_nonzero method - Python

Last Updated : 20 Sep, 2025

When working with arrays, sometimes you need to quickly count how many elements are not equal to zero. NumPy makes this super easy with the numpy.count_nonzero() function.

This is useful when:

  • You want to count valid entries in datasets.
  • You’re filtering out missing (zero) values.
  • You need quick statistics on arrays.

Example: Let’s start with the simplest example to understand how it works.


Output
3

Explanation: array is [0, 1, 0, 2, 3] and non-zero elements are 1, 2, 3 -> total 3 values.

Syntax

numpy.count_nonzero(arr, axis=None)

Parameters:

  • arr: array_like - Input array.
  • axis: int or tuple, optional - None counts over the whole array; int/tuple counts along given axis (row/column).

Return Value: int (if axis=None) or array of ints (if axis is given). Represents the count of non-zero elements.

Examples

Example 1: In this example, we count all non-zero elements in a 2D array.


Output
6

Explanation: There are 6 values that are not zero.

Example 2: Here, we count non-zero elements column-wise using axis=0.


Output
[1 1 2 1 2]

Explanation:

  • Column 0 -> 1 non-zero (5) and Column 1 -> 1 non-zero (1)
  • Column 2 -> 2 non-zeros (2, 6), Column 3 -> 1 non-zero (3) and Column 4 -> 2 non-zeros (4, 7)

Example 3: This example counts non-zero elements row-wise using axis=1.


Output
[2 3]

Explanation: Row 0 -> 2 non-zeros (3, 4) and Row 1 -> 3 non-zeros (5, 6, 7)

Comment
Article Tags:
Article Tags: