Fix Python – How to count the number of true elements in a NumPy bool array

Question

Asked By – norio

I have a NumPy array ‘boolarr’ of boolean type. I want to count the number of elements whose values are True. Is there a NumPy or Python routine dedicated for this task? Or, do I need to iterate over the elements in my script?

Now we will see solution for issue: How to count the number of true elements in a NumPy bool array


Answer

You have multiple options. Two options are the following.

boolarr.sum()
numpy.count_nonzero(boolarr)

Here’s an example:

>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False,  True],
       [ True, False,  True],
       [ True, False,  True]], dtype=bool)

>>> boolarr.sum()
5

Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.

>>> np.count_nonzero(boolarr)
5

This question is answered By – David Alber

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0