Created
December 9, 2013 16:50
-
-
Save andrewgiessel/7875659 to your computer and use it in GitHub Desktop.
continuous regions in an boolean array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def contiguous_regions(condition): | |
"""Finds contiguous True regions of the boolean array "condition". Returns | |
three 1d arrays: start indicies, stop indicies and lengths of contigous regions | |
""" | |
d = np.diff(condition) | |
idx, = d.nonzero() | |
idx += 1 # need to shift indices because of diff | |
if condition[0]: | |
# If the start of condition is True prepend a 0 | |
idx = np.r_[0, idx] | |
if condition[-1]: | |
# If the end of condition is True, append the length of the array | |
idx = np.r_[idx, condition.size] # Edit | |
starts = idx[0::2] | |
stops = idx[1::2] | |
lengths = stops - starts | |
return starts, stops, lengths |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment