[Numpy-discussion] contiguous regions

Gregor Thalhammer gregor.thalhammer@gmail....
Thu Nov 20 11:24:18 CST 2008

John Hunter schrieb:
> I frequently want to break a 1D array into regions above and below
> some threshold, identifying all such subslices where the contiguous
> elements are above the threshold.  I have two related implementations
> below to illustrate what I am after.  The first "crossings" is rather
> naive in that it doesn't handle the case where an element is equal to
> the threshold (assuming zero for the threshold in the examples below).
>  The second is correct (I think) but is pure python.  Has anyone got a
> nifty numpy solution for this?
> import numpy as np
> import matplotlib.pyplot as plt
> t = np.arange(0.0123, 2, 0.05)
> s = np.sin(2*np.pi*t)
here my proposal, needs some polishing:

mask = (s>0).astype(int8)
d = diff(mask)
idx, = d.nonzero()
#now handle the cases that s is above threshold at beginning or end of 
if d[idx[0]] == -1:
   idx = r_[0, idx]
if d[idx[-1]] == 1:
   idx = r_[idx, len(s)]
idx.shape = (-1,2)


More information about the Numpy-discussion mailing list