numpy/scipy中的向量化索引/切片? [英] vectorized indexing/slicing in numpy/scipy?
问题描述
我有一个数组A,并且有一个切片索引(s,t)的列表,我们称此列表为L.
I have an array A, and I have a list of slicing indices (s,t), let's called this list L.
我想找到A [s1:t1],A [s2:t2] ...的85个百分位数
I want to find the 85 percentiles of A[s1:t1], A[s2:t2] ...
是否有一种方法可以在numpy中向量化这些操作?
Is there a way to vectorize these operations in numpy?
ans = []
for (s,t) in L:
ans.append( numpy.percentile( A[s:t], 85) );
看起来很麻烦.
非常感谢!
PS:假定s1<是安全的. s2 .... t1< t2 .....这实际上只是一个滑动窗口百分位数问题.
PS: it's safe to assume s1 < s2 .... t1 < t2 ..... This is really just a sliding window percentile problem.
推荐答案
鉴于您正在处理不均匀的间隔(即,切片的大小不同),不,没有办法让numpy做只需一个函数调用即可.
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.
如果是均匀的切片大小,则可以使用各种技巧来完成,如@eat注释.
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]
这篇关于numpy/scipy中的向量化索引/切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!