saud saud - 7 months ago 15
Python Question

How do I identify sequences of values in a boolean array?

I have a long boolean array:

bool_array = [ True, True, True, True, True, False, False, False, False, False, True, True, True, False, False, True, True, True, True, False, False, False, False, False, False, False ]


I need to figure out where the values flips, i.e., the addresses where sequences of
True
and
False
begin. In this particular case, I would want to get

index = [0, 5, 10, 13, 15, 19, 26]


Is there an easy way to do without manually looping to check every ith element with the (i+1)th?

Answer

As a more efficient approach for large datasets, in python 3.X you can use accumulate and groupby function from itertools module.

>>> from itertools import accumulate, groupby
>>> [0] + list(accumulate(sum(1 for _ in g) for _,g in groupby(bool_array)))
[0, 5, 10, 13, 15, 19, 26]