You may also consider, well, counting the nonzero values:

import numba as nb

@nb.njit()
def count_loop(a):
    s = 0
    for i in a:
        if i != 0:
            s += 1
    return s

I know it seems wrong, but bear with me:

import numpy as np
import numba as nb

@nb.njit()
def count_loop(a):
    s = 0
    for i in a:
        if i != 0:
            s += 1
    return s

@nb.njit()
def count_len_nonzero(a):
    return len(np.nonzero(a)[0])

@nb.njit()
def count_sum_neq_zero(a):
    return (a != 0).sum()

np.random.seed(100)
a = np.random.randint(0, 3, 1000000000, dtype=np.uint8)
c = np.count_nonzero(a)
assert count_len_nonzero(a) == c
assert count_sum_neq_zero(a) == c
assert count_loop(a) == c

%timeit count_len_nonzero(a)
# 5.94 s ± 141 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit count_sum_neq_zero(a)
# 848 ms ± 80.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit count_loop(a)
# 189 ms ± 4.41 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

It is in fact faster than np.count_nonzero, which can get quite slow for some reason:

%timeit np.count_nonzero(a)
# 4.36 s ± 69.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Answer from javidcf on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-count_nonzero-method-python
Numpy count_nonzero method - Python - GeeksforGeeks
September 20, 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.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.nonzero.html
numpy.nonzero — NumPy v2.5 Manual
Return indices that are non-zero in the flattened version of the input array. ... Equivalent ndarray method. ... Counts the number of non-zero elements in the input array.
Top answer
1 of 4
6

You may also consider, well, counting the nonzero values:

import numba as nb

@nb.njit()
def count_loop(a):
    s = 0
    for i in a:
        if i != 0:
            s += 1
    return s

I know it seems wrong, but bear with me:

import numpy as np
import numba as nb

@nb.njit()
def count_loop(a):
    s = 0
    for i in a:
        if i != 0:
            s += 1
    return s

@nb.njit()
def count_len_nonzero(a):
    return len(np.nonzero(a)[0])

@nb.njit()
def count_sum_neq_zero(a):
    return (a != 0).sum()

np.random.seed(100)
a = np.random.randint(0, 3, 1000000000, dtype=np.uint8)
c = np.count_nonzero(a)
assert count_len_nonzero(a) == c
assert count_sum_neq_zero(a) == c
assert count_loop(a) == c

%timeit count_len_nonzero(a)
# 5.94 s ± 141 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit count_sum_neq_zero(a)
# 848 ms ± 80.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit count_loop(a)
# 189 ms ± 4.41 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

It is in fact faster than np.count_nonzero, which can get quite slow for some reason:

%timeit np.count_nonzero(a)
# 4.36 s ± 69.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2 of 4
3

In case you need it really fast for large arrays you could even use numbas prange to process the count in parallel (for small arrays it will be slower due to the parallel-processing overhead).

import numpy as np
from numba import njit, prange

@njit(parallel=True)
def parallel_nonzero_count(arr):
    flattened = arr.ravel()
    sum_ = 0
    for i in prange(flattened.size):
        sum_ += flattened[i] != 0
    return sum_

Note that when you use numba you normally want to write out your loops because that's what numba is really very good at optimizing.

I actually timed it against the other solutions mentioned here (using my Python module simple_benchmark):

Code to reproduce:

import numpy as np
from numba import njit, prange

@njit
def n_nonzero(a):
    return a[a != 0].size

@njit
def count_non_zero(np_arr):
    return len(np.nonzero(np_arr)[0])

@njit() 
def methodB(a): 
    return (a!=0).sum()

@njit(parallel=True)
def parallel_nonzero_count(arr):
    flattened = arr.ravel()
    sum_ = 0
    for i in prange(flattened.size):
        sum_ += flattened[i] != 0
    return sum_

@njit()
def count_loop(a):
    s = 0
    for i in a:
        if i != 0:
            s += 1
    return s

from simple_benchmark import benchmark

args = {}
for exp in range(2, 20):
    size = 2**exp
    arr = np.random.random(size)
    arr[arr < 0.3] = 0.0
    args[size] = arr

b = benchmark(
    funcs=(n_nonzero, count_non_zero, methodB, np.count_nonzero, parallel_nonzero_count, count_loop),
    arguments=args,
    argument_name='array size',
    warmups=(n_nonzero, count_non_zero, methodB, np.count_nonzero, parallel_nonzero_count, count_loop)
)
Find elsewhere
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.nonzero.html
numpy.nonzero — NumPy v2.1 Manual
Return indices that are non-zero in the flattened version of the input array. ... Equivalent ndarray method. ... Counts the number of non-zero elements in the input array.
🌐
JAX Documentation
docs.jax.dev › en › latest › _autosummary › jax.numpy.count_nonzero.html
jax.numpy.count_nonzero — JAX documentation
Return the number of nonzero elements along a given axis. JAX implementation of numpy.count_nonzero().
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › numpy count nonzero values in python
NumPy Count Nonzero Values in Python - Spark By {Examples}
March 27, 2024 - NumPy count_nonzero() function in Python is used to count the number of nonzero elements present in the one-dimensional or multi-dimensional array. This function has 3 parameters as arr, axis, and keepdims.
🌐
Python Pool
pythonpool.com › home › blog › 4 examples to use numpy count_nonzero() function
4 Examples to Use Numpy count_nonzero() Function - Python Pool
April 14, 2021 - The Numpy count_nonzero() function is used to give the count of the nonzero elements present in the multidimensional array. With the help of this function, we can find the count of the elements in the multidimensional array which are not zero.
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-63.php
NumPy: Get the number of nonzero elements in an array - w3resource
August 29, 2025 - Write a NumPy program to get the number of non-zero elements in an array. ... # Importing the NumPy library with an alias 'np' import numpy as np # Creating a 2x3 NumPy array 'x' containing specific values x = np.array([[0, 10, 20], [20, 30, 40]]) # Displaying the original 2x3 array 'x' print("Original array:") print(x) # Counting the number of non-zero elements in the array 'x' using np.count_nonzero print("Number of non-zero elements in the above array:") print(np.count_nonzero(x))
🌐
Runebook.dev
runebook.dev › en › docs › numpy › reference › generated › numpy.count_nonzero
Understanding and Using numpy.count_nonzero() Effectively
The Problem You want to count non-zero elements for each row or column but you get a single number or an unexpected array. The Fix Specify the axis correctly. axis=0 counts along the columns (vertical), and axis=1 counts along the rows (horizontal).