Skip to content

Instantly share code, notes, and snippets.

@andrewgiessel
Created December 9, 2013 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgiessel/7875659 to your computer and use it in GitHub Desktop.
Save andrewgiessel/7875659 to your computer and use it in GitHub Desktop.
continuous regions in an boolean array
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