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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:
which can be extended to D dimensions.
The results are:
Prediction:
Target:
Count of correct prediction for D=1:
1
Count of correct prediction for D=2:
2
If you wish to do a per-row count, supply
axis=1
tosum
:Similarly, with
np.count_nonzero
: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 dict :
But this won't work :
Maybe this will help someone.
You have multiple options. Two options are the following.
Here's an example:
Of course, that is a
bool
-specific answer. More generally, you can usenumpy.count_nonzero
.