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?
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.
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.
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].
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
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With