[Numpy-discussion] finding longest contiguous array slices
Tom Krauss
thomas.p.krauss at gmail.com
Sun May 22 08:13:28 EDT 2011
On Sat, May 21, 2011 at 5:55 AM, Ben Elliston <bje at air.net.au> wrote:
> I have a 3-d array of booleans (5 x 5 x 1000, say) and would like to
> return a 5 x 5 of array slices containing the longest contiguous
> sequence of True values along the z axis.
What do you mean by "5 x 5 of array slices containing the longest
contiguous sequence of True values along the z axis"?
So you want a 5x5xN slice of the array that is all True?
Basically I would first find the index of the longest run of True,
then form the slice.
Here's an example borrowing heavily from "numpy-native" response here
http://stackoverflow.com/questions/1066758/find-length-of-sequences-of-identical-values-in-a-numpy-array
x = np.random.rand(5,5,1000)>.01
y = x.all(0).all(0) # <--- is this right? You want all 5x5 values True
# make sure all runs of ones are well-bounded
bounded = np.hstack(([0], y, [0]))
# get 1 at run starts and -1 at run ends
difs = np.diff(bounded)
run_starts, = np.where(difs > 0)
run_ends, = np.where(difs < 0)
idx = np.argmax(run_ends - run_starts)
x[:,:,run_starts[idx]:run_ends[idx]] # here is your slice
If by "5 x 5 of array slices containing the longest contiguous
sequence of True values along the z axis" you mean a different slice
for each of the 5x5 sub-arrays, then you can use similar idea but find
the run_starts and run_ends for each x[i,j].
More information about the NumPy-Discussion
mailing list