Find Trues segments in a numpy array

Is there a good way to find Trues patches in a massive boolean array? If I have an array like:

x = numpy.array([True,True,False,True,True,False,False]) 

Is it possible to get an array of indices like:

 starts = [0,3] ends = [1,4] 

or any other way of storing this information. I know this can be done with some complex loops, but I'm looking for a better way.

+5
source share
1 answer

You can put x with Falses (one at the beginning and one at the end) and use np.diff . "Diff" of 1 means the transition from False to True, and -1 means the transition from True to False.

The agreement should represent the end of the range as an index one after the last. This example is consistent with the convention (you can easily use ends-1 instead of ends to get an array in your question):

 x1 = np.hstack([ [False], x, [False] ]) # padding d = np.diff(x1.astype(int)) starts = np.where(d == 1)[0] ends = np.where(d == -1)[0] starts, ends => (array([0, 3]), array([2, 5])) 
+7
source

All Articles