How to count number of consecutive Trues in a numpy array along a given axis?

I have for example the following np array

array([[ True, False, False],
       [False,  True,  True],
       [ True,  True,  True],
       [False,  True,  True],
       [False,  True,  True],
       [ True, False, False],
       [ True,  True, False],
       [False, False,  True]])

I want to count the number of consecutive Trues along the columns, so in the above example, the first column contains 3 blocks of consecutive Trues, the second column contains 2 blocks, and the third contains 2 blocks. The output should then be

array([3, 2, 2])

I know I can do loops for each columns, like in this answer for a one-dimensional array, but what is a numpy-way for doing this on a 2-d array?

>Solution :

Use boolean arithmetic to identify the True that are not followed by a True (using slicing and pad), then sum the True per column:

out = ((a != np.pad(a[1:], ((0,1), (0,0)), constant_values=False))
       & a).sum(axis=0)

Or:

out = (a & ~np.pad(a[1:], ((0,1), (0,0)), constant_values=False)).sum(axis=0)

Output:

array([3, 2, 2])

Leave a Reply