1

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?

TTY
  • 137
  • 7

3 Answers3

1

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])
mozway
  • 194,879
  • 13
  • 39
  • 75
1

You could do this by comparing elements with their successor along the first axis and adding up the transitions from False to True to the True values of the first row:

A[0,:] + (A[:-1,:]<A[1:,:]).sum(axis=0)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0
def count_consecutive_trues(arr, axis):
        consecutive_counts = []
        for row in arr:
                count = 0
                max_count = 0
                for value in row:
                        if value:
                                count += 1
                                max_count = max(max_count, count)
                        else:
                                count = 0
                consecutive_counts.append(max_count)
        return consecutive_counts
Tyler2P
  • 2,324
  • 26
  • 22
  • 31