I'm looking to count the number of False
values that precede at least one True
value for each row in a 2D Numpy array.
For example the desired function would act as below:
>>> x = np.array([[0,0,1,0],[1,1,0,1],[1,1,1,1]], dtype='bool')
>>> x
array([[False, False, True, False],
[ True, True, False, True],
[ True, True, True, True]])
>>> foo(x)
3
The result is 3 since the first row has two False
before a True
value, with the final False ignored. There's one False
that precedes True
on the second row and none on the third.
Rows with no True
value (all False) count as 0
.
Is there a vectorised means of calculating this without iterating through the rows? Currently the only ways I have would be counting transitions with numpy.diff()
or iterating through each row individually.