Home > OS >  How to count the number of true elements in each row of a NumPy bool array
How to count the number of true elements in each row of a NumPy bool array

Time:03-23

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

CodePudding user response:

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])
  • Related