Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading