Saturday, September 6, 2025
HomeLanguagesNumpy count_nonzero method | Python

Numpy count_nonzero method | Python

numpy.count_nonzero() function counts the number of non-zero values in the array arr.

Syntax : numpy.count_nonzero(arr, axis=None)

Parameters :
arr : [array_like] The array for which to count non-zeros.
axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of arr.

Return : [int or array of int] Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.

Code #1 :




# Python program explaining
# numpy.count_nonzero() function
  
# importing numpy as geek 
import numpy as geek
  
arr = [[0, 1, 2, 3, 0], [0, 5, 6, 0, 7]]
  
gfg = geek.count_nonzero(arr)
  
print (gfg) 


Output :

6

 
Code #2 :




# Python program explaining
# numpy.count_nonzero() function
  
# importing numpy as geek 
import numpy as geek
  
arr = [[0, 1, 2, 3, 4], [5, 0, 6, 0, 7]]
  
gfg = geek.count_nonzero(arr, axis = 0)
  
print (gfg) 


Output :

7
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11805 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6753 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS