[SciPy-user] indices of consecutive elements

alex argriffi at ncsu.edu
Tue Dec 2 16:50:11 EST 2008


Here's a way that uses convolution.

from numpy import *
v = array([0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 
1, 1, 0])
n=4
c = convolve(v, ones(n+1))[:len(v)]
where((c==n) & (v==0))

This gives (array([ 6, 19]),) where 6 and 19 are off by one
from the correct end indices.
Maybe there's a more efficient way to do a convolution with this
kind of rectangular window, using the cumulative sum for example.

Alex



Daniel Ashbrook wrote:
> I'm trying to figure out a way to return the indices of the start and
> end of a run of consecutive elements that match some condition, but only
> if there are more than a certain number.
>
> For example, take the array (with indices in comment for clarity):
>
> #0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22
> [0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0]
>
> I want to find the start and end indices of all runs of 1s with length
> of 4 or longer; so here the answer would be:
>
> [[2,5], [15,18]]
>
> Is there a reasonable way to do this without looping? I've been playing
> around with diff() and where() but without too much progress.
>
> Thanks,
>
>
> dan
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>   




More information about the SciPy-User mailing list