vectorized indexing/slicing in numpy/scipy?

南楼画角 提交于 2020-01-04 07:51:19

问题


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]


来源:https://stackoverflow.com/questions/6877008/vectorized-indexing-slicing-in-numpy-scipy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!