[SOLVED] How to count the number of true elements in each row of a NumPy bool array

Issue

I have a NumPy array ‘boolarr’ of boolean type. I want to count the number of elements whose values are True in each row. Is there a NumPy or Python routine dedicated for this task?

For example, consider the code below:

>>> 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)

The count of each row would give the following results:

1
2
2

Solution

In [48]: boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=bool)
In [49]: boolarr
Out[49]: 
array([[False, False,  True],
       [ True, False,  True],
       [ True, False,  True]])

Just use sum:

In [50]: np.sum(boolarr, axis=1)
Out[50]: array([1, 2, 2])

The True count as 1 when doing addition.

Or:

In [54]: np.count_nonzero(boolarr, axis=1)
Out[54]: array([1, 2, 2])

Answered By – hpaulj

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *