Numpy blockwise reduce操作

2024-05-19 10:08:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为自己是一个有经验的numpy用户,但我无法找到解决以下问题的方法。假设有以下阵列:

# sorted array of times
t = numpy.cumsum(numpy.random.random(size = 100))
#  some values associated with the times
x = numpy.random.random(size=100)
# some indices into the time/data array
indices = numpy.cumsum(numpy.random.randint(low = 1, high=10,size = 20)) 
indices = indices[indices <90] # respect size of 100
if len(indices) % 2: # make number of indices even
    indices = indices[:-1]

# select some starting and end indices
istart = indices[0::2]
iend   = indices[1::2]

我现在想要的是减少值数组x,给定由istartiend表示的间隔。一、 e

^{pr2}$

我已经在google上搜索了很多,但是我能找到的只是通过stride_tricks进行的分块操作,它只允许常规的块。如果不执行pyhthon循环,我无法找到解决方案:-( 在我的实际应用程序中,数组要大得多,性能也很重要,所以我暂时使用numba.jit。在

有没有我缺少的可以做到这一点的numpy函数?在


Tags: ofthe用户numpysizerandomsome数组
2条回答

您可以使用^{}
像这样:

what_i_want = np.array([np.max(x[np.r_[ib:ie]]) for ib,ie in zip(istart,iend)])

你看过^{}了吗?使用np.maximum,您可以执行以下操作:

>>> np.maximum.reduceat(x, indices)

这将产生沿片x[indices[i]:indices[i+1]]的最大值。为了得到你想要的(x[indices[2i]:indices[2i+1]),你可以这样做

^{pr2}$

如果您不介意x[inidices[2i-1]:indices[2i]]的额外计算。结果如下:

>>> numpy.array([numpy.max(x[ib:ie]) for ib,ie in zip(istart,iend)])
array([ 0.60265618,  0.97866485,  0.78869449,  0.79371198,  0.15463711,
        0.72413702,  0.97669218,  0.86605981])

>>> np.maximum.reduceat(x, indices)[::2]
array([ 0.60265618,  0.97866485,  0.78869449,  0.79371198,  0.15463711,
        0.72413702,  0.97669218,  0.86605981])

相关问题 更多 >

    热门问题