How to count number of consecutive Trues in a numpy array along a given axis?
Question:
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?
Answers:
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])
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)
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?
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])
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)