2016-11-21 80 views
9

我認爲自己是一個經驗豐富的numpy用戶,但我無法找到解決方案,以解決以下問題。假設有下面的數組:Numpy blockwise減少操作

# 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.g. use max reduce, I'll probably also need mean and stdv 
what_i_want = numpy.array([numpy.max(x[is:ie]) for is,ie in zip(istart,iend)]) 

我已經用Google搜索了很多,但通過stride_tricks只允許普通塊所有我能找到的是按塊操作。我沒能找到一個解決方案,而不執行pyhthon環:-( 在我的實際應用中的數組是更大,性能此事做,所以我用numba.jit的時刻。

是否有任何numpy的功能我缺少這是能夠做到這一點

+0

'x'總會在'[0,1)'中有浮點數嗎? – Divakar

+0

編號'x'通常是一個更復雜的數組結構。 –

回答

7

你有沒有看着ufunc.reduceat隨着np.maximum,你可以這樣做:

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

其產生沿切片x[indices[i]:indices[i+1]]的最大值。爲了得到你想要的(x[indices[2i]:indices[2i+1]),你可以做

>>> np.maximum.reduceat(x, indices)[::2] 

,如果你不介意的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]) 
+1

我學到了新的東西... thx – piRSquared

+0

真棒,那就是我一直在尋找的東西。我可以只保留一個數組中的所有索引,然後我不做任何開銷計算:)也許我應該提高我的谷歌搜索技能... –

0

可以使用numpy.r_
是這樣的:

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