Search code examples
pythonnumpybooleancumsum

get index of the first block of at least n consecutive False values in boolean array


I have a numpy boolean array

w=np.array([True,False,True,True,False,False,False])

I would like to get the index of the first time there are at n_at_least false values. For instance here

`n_at_least`=1 -> desired_index=1

`n_at_least`=3 -> desired_index=4

I have tried

np.cumsum(~w)

which does increase every time a False value is encountered. However, when True is encountered the counter is not starting from 0 again so I only get the total count of False elements rather than the count of the last consecutive ones.


Solution

  • I think for this linear search operation a python implementation is ok. My suggestion looks like this:

    def find_block(arr, n_at_least=1):
        current_index = 0
        current_count = 0
        for index, item in enumerate(arr):
             if item:
                 current_count = 0
                 current_index = index + 1
             else:
                 current_count += 1
             if current_count == n_at_least:
                 return current_index
        return None # Make sure this is outside for loop
    

    Running this function yields the following outputs:

    >>> import numpy
    >>> w = numpy.array([True, False, True, True, False, False, False])
    >>> find_block(w, n_at_least=1)
    1
    >>> find_block(w, n_at_least=3)
    4
    >>> find_block(w, n_at_least=4)
    >>> # None