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

前端 未结 4 672
天命终不由人
天命终不由人 2020-12-31 06:59

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         


        
4条回答
  •  有刺的猬
    2020-12-31 07:57

    This will tell you where:

    >>> import numpy as np
    >>> np.argwhere(np.diff(bool_array)).squeeze()
    array([ 4,  9, 12, 14, 18])
    

    np.diff calculates the difference between each element and the next. For booleans, it essentially interprets the values as integers (0: False, non-zero: True), so differences appear as +1 or -1 values, which then get mapped back to booleans (True when there is a change).

    The np.argwhere function then tells you where the values are True --- which are now the changes.

提交回复
热议问题