Count consecutive occurences of values varying in length in a numpy array
If you already have a numpy array, this is probably going to be faster:
>>> condition = np.array([True,True,True,False,False,True,True,False,True])
>>> np.diff(np.where(np.concatenate(([condition[0]],
condition[:-1] != condition[1:],
[True])))[0])[::2]
array([3, 2, 1])
It detects where chunks begin, has some logic for the first and last chunk, and simply computes differences between chunk starts and discards lengths corresponding to False
chunks.
Here's a solution using itertools
(it's probably not the fastest solution):
import itertools
condition = [True,True,True,False,False,True,True,False,True]
[ sum( 1 for _ in group ) for key, group in itertools.groupby( condition ) if key ]
Out:
[3, 2, 1]