vectorized indexing/slicing in numpy/scipy?

2019-07-20 23:48发布

问题:

I have an array A, and I have a list of slicing indices (s,t), let's called this list L.

I want to find the 85 percentiles of A[s1:t1], A[s2:t2] ...

Is there a way to vectorize these operations in numpy?

ans = []
for (s,t) in L:
   ans.append( numpy.percentile( A[s:t], 85) ); 

looks cumbersome.

Thanks a lot!

PS: it's safe to assume s1 < s2 .... t1 < t2 ..... This is really just a sliding window percentile problem.

回答1:

Given that you're dealing with a non-uniform interval (i.e. the slices aren't the same size), no, there's no way to have numpy do it in a single function call.

If it was a uniform slice size, then you could do so with various tricks, as @eat commented.

However, what's wrong with a list comprehension? It's exactly equivalent to your loop above, but it looks "cleaner" if that's what you're worried about.

ans = [numpy.percentile(A[s:t], 85) for s,t in L]