Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 379
norio Avatar asked Oct 04 '22 08:10

norio


People also ask

How do you count true numbers?

To count the number of TRUE entries, which here is 5, the formula =COUNTIF(A1:A6,TRUE) applied to the column should work, but it always returns the result 1. On the other hand, the formula =COUNTIF(A1:A6,FALSE) works correctly on a similar column got by pulling down FALSE.

How do you count elements in an array in Python?

Python len() method enables us to find the total number of elements in the array/object. That is, it returns the count of the elements in the array/object.

Is there a count function in numpy?

NumPy count() function The count() function is used to return an array with the count values of non-overlapping occurrences(unique) of a given substring in the range [start, end].


2 Answers

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
like image 130
David Alber Avatar answered Oct 07 '22 10:10

David Alber


That question solved a quite similar question for me and I thought I should share :

In raw python you can use sum() to count True values in a list :

>>> sum([True,True,True,False,False])
3

But this won't work :

>>> sum([[False, False, True], [True, False, True]])
TypeError...
like image 44
Guillaume Gendre Avatar answered Oct 07 '22 09:10

Guillaume Gendre