🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Count values in an array with conditions | note.nkmk.me
February 3, 2024 - Note that the axis argument was introduced to np.count_nonzero() in NumPy version 1.12, and keepdims in version 1.19. In contrast, both arguments have been available in np.sum() since version 1.7. Therefore, for versions older than 1.12, consider using np.sum().
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.count_nonzero.html
numpy.count_nonzero — NumPy v2.5 Manual
Counts the number of non-zero values in the array a · A non-zero value is one that evaluates to truthful in a boolean context, including any non-zero number and any string that is not empty. This function recursively counts how many elements in a (and its sub-arrays) are non-zero values
🌐
Lightrun
lightrun.com › answers › numpy-numpy-use-count_nonzero-instead-of-sum-for-boolean-arrays
Use count_nonzero instead of sum for boolean arrays
More generally, you can use numpy.count_nonzero . ... In raw python you can use sum() to count True values in a list :...Read more >
🌐
Codecademy Forums
discuss.codecademy.com › computer science
Why is does count() yield the same result as sum()? - Computer Science - Codecademy Forums
February 28, 2023 - In the project Detecting Product Defects with Probability (Probability for Datascience), in task 13 it is asked to calculate the number of values above 10 in a certain array. I used np.count_nonzero(array>=10) but the hint tab suggests to use sum(array >= 10).
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.count_nonzero.html
numpy.count_nonzero — NumPy v2.2 Manual
Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.count_nonzero.html
numpy.count_nonzero — NumPy v2.6.dev0 Manual
Counts the number of non-zero values in the array a · A non-zero value is one that evaluates to truthful in a boolean context, including any non-zero number and any string that is not empty. This function recursively counts how many elements in a (and its sub-arrays) are non-zero values
Find elsewhere
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)
)
🌐
Bomberbot
bomberbot.com › python › mastering-numpys-count_nonzero-a-comprehensive-guide-for-python-enthusiasts
Mastering NumPy's count_nonzero(): A Comprehensive Guide for Python Enthusiasts - Bomberbot
As Python enthusiasts, we're always concerned about performance. count_nonzero() is highly optimized and generally faster than using numpy.sum() with a boolean mask, especially for large arrays.
Top answer
1 of 1
2

(EDITED: I somewhat overlooked that you were using NumPy arrays)

To replace:

sum(map(lambda base1 : base1 == x, base1)) 

or:

count1 = sum([base1 == x for base1 in base1])

the best approach depends if your input is a list or a NumPy array.

  • if you have a list, you could use the list.count() method:
base1.count(x)
  • if you have a NumPy array, as this seems to be the case, you could use np.count_nonzero() for NumPy arrays:
import numpy as np


np.count_nonzero(base1 == x)

However, this will create a potentially large temporary object. This can be solved by creating your own function and accelerate it with Cython (not shown) or, even better, with Numba, as shown below:

import numba as nb


@nb.jit
def nb_count_equal(arr, value):
    result = 0
    for x in arr:
        if x == value:
            result += 1
    return result

which would also be faster than np.count_nonzero() in this case.

Testing some of these approaches on toy data shows that they give the same result:

np.random.seed(0)  # to ensure reproducible results

arr = np.random.randint(0, 20, 1000)
y = 10

print(sum(map(lambda x: x == y, arr)))
# 41
print(sum([x == y for x in arr]))
# 41
print(np.count_nonzero(arr == y))
# 41
print(nb_count_equal(arr, y))
# 41

with the following timing:

arr = np.random.randint(0, 20, 1000000)
y = 10

%timeit sum(map(lambda x: x == y, arr))
# 1 loop, best of 3: 2.54 s per loop
%timeit sum([x == y for x in arr])
# 1 loop, best of 3: 2.43 s per loop
%timeit np.count_nonzero(arr == y)
# 1000 loops, best of 3: 574 µs per loop
%timeit nb_count_equal(arr, y)
# 1000 loops, best of 3: 224 µs per loop

Note, the previous suggestion of removing the square brackets to avoid creating a temporary list is slower than just having a generator because of the way sum() is implemented, but it would definitely have the advantage of avoiding to create unnecessary temporary lists.


Finally, if you are doing this counting multiple times, it may be more beneficial to do this in a single go with np.unique().

🌐
Python Guides
pythonguides.com › python-numpy-count
Np.count_nonzero() Function In NumPy - Python Guides
May 16, 2025 - While count_nonzero() is specifically designed for counting; you can achieve the same result using NumPy’s sum() function with Boolean arrays in Python:
🌐
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.
Top answer
1 of 5
42
import numpy as np

a = np.array([[1, 0, 1],
              [2, 3, 4],
              [0, 0, 7]])

columns = (a != 0).sum(0)
rows    = (a != 0).sum(1)

The variable (a != 0) is an array of the same shape as original a and it contains True for all non-zero elements.

The .sum(x) function sums the elements over the axis x. Sum of True/False elements is the number of True elements.

The variables columns and rows contain the number of non-zero (element != 0) values in each column/row of your original array:

columns = np.array([2, 1, 3])
rows    = np.array([2, 3, 1])

EDIT: The whole code could look like this (with a few simplifications in your original code):

ANOVAInputMatrixValuesArray = zeros([len(TestIDs), 9], float)
for j, TestID in enumerate(TestIDs):
    ReadOrWrite = 'Read'
    fileName = inputFileName
    directory = GetCurrentDirectory(arguments that return correct directory)
    # use directory or filename to get the CSV file?
    with open(directory, 'r') as csvfile:
        ANOVAInputMatrixValuesArray[j,:] = loadtxt(csvfile, comments='TestId', delimiter=';', usecols=(2,))[:9]

nonZeroCols = (ANOVAInputMatrixValuesArray != 0).sum(0)
nonZeroRows = (ANOVAInputMatrixValuesArray != 0).sum(1)

EDIT 2:

To get the mean value of all columns/rows, use the following:

colMean = a.sum(0) / (a != 0).sum(0)
rowMean = a.sum(1) / (a != 0).sum(1)

What do you want to do if there are no non-zero elements in a column/row? Then we can adapt the code to solve such a problem.

2 of 5
24

A fast way to count nonzero elements per row in a scipy sparse matrix m is:

np.diff(m.tocsr().indptr)

The indptr attribute of a CSR matrix indicates the indices within the data corresponding to the boundaries between rows. So calculating the difference between each entry will provide the number of non-zero elements in each row.

Similarly, for the number of nonzero elements in each column, use:

np.diff(m.tocsc().indptr)

If the data is already in the appropriate form, these will run in O(m.shape[0]) and O(m.shape[1]) respectively, rather than O(m.getnnz()) in Marat and Finn's solutions.

If you need both row and column nozero counts, and, say, m is already a CSR, you might use:

row_nonzeros = np.diff(m.indptr)
col_nonzeros = np.bincount(m.indices)

which is not asymptotically faster than first converting to CSC (which is O(m.getnnz())) to get col_nonzeros, but is faster because of implementation details.

🌐
Runebook.dev
runebook.dev › en › docs › numpy › reference › generated › numpy.count_nonzero
Understanding and Using numpy.count_nonzero() Effectively
Many developers prefer this method because it explicitly shows that you are summing up the True values, which can be more readable. If you not only want to count but also need the indices of the non-zero elements, np.where() is the perfect tool. ... import numpy as np arr = np.array([1, 0, 5, 0, 8, 0]) # Find the indices of non-zero elements indices = np.where(arr != 0) print(f"Indices of non-zero elements: {indices}") # Output: Indices of non-zero elements: (array([0, 2, 4]),) # You can then get the count from the length of the result count = len(indices[0]) print(f"Count from np.where(): {count}") # Output: Count from np.where(): 3