[Numpy-discussion] Find contiguous sequences of booleans in arrays
Charles R Harris
Mon Sep 17 12:34:48 CDT 2007
On 9/17/07, Kurdt Bane <email@example.com> wrote:
> Hi to all,
> I've got an 1-D array of bools and I'd like to find the length of the
> first contiguous sequence of True values, starting from position  of the
> (That's equivalent to find the position of the first occurrence of False
> in the array).
> The problem is trivial, but I was wondering: what's the best (fastest,
> cleanest, most pythonesque) way to do it in numpy? And what if I want to get
> a list of all the contiguous sequences of True values, above a given
You can find the start of all runs after the first by
In : a = array([1,1,1,0,1,1,0,0,1], dtype=bool)
In : s = arange(1,len(a))[a[0:-1] ^ a[1:]]
In : s
Out: array([3, 4, 6, 8])
i.e. The first run is a[0:3], the second a[3:4], etc., and the runs
alternate between true and false.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Numpy-discussion