2016-08-15 53 views
1

給定一個大的numpy浮點型數組和2個索引數組我想要一個優雅的方式來按照以下規則對給定索引之間包含的所有值進行求和:指數陣列之間具有環繞條件的Numpy總和

    當索引1>索引0,總和在一條直線前進的方式
  • 當索引1 <索引0,求和「的wraparounds」的價值觀發生

因此,例如:

import numpy as np 

# Straight forward summation when index1 > index0 
values = np.array([0.,10.,20.,30.,40.,50.,60.,70.]) 
index0 = np.array([0,3]) 
index1 = np.array([2,6]) 
# Desired Result: np.array([30,180]) # (0+10+20),(30+40+50+60) 

# Wrap around condition when index1 < index0 
index0 = np.array([5]) 
index1 = np.array([1]) 
# Result: np.array([190]) # (50+60+70+0+10) 

因爲我處理相當大的陣列,我正在尋找可能的話優雅numpy的爲中心的解決方案。

+0

你能仔細檢查你的榜樣,邊界和預期結果似乎離... – Julien

+0

這些範圍的莫不是重疊,像'索引0 = np.array([ 0,3])和index1 = np.array([4,6])'? – Divakar

+0

@Divakar是的。 'index0'和'index1'也可以表示爲一個單對的列表,例如:index = np.array([[0,4],[3,6],...])... if這有助於。 – Fnord

回答

2

關於什麼:

# store all cumulative sums (adding 0 at the start for the empty sum) 
cs = np.insert(np.cumsum(values), 0, 0) 

# then for each indexing get the result in constant time (linear in index0/1 size): 
result = np.where(index0 < index1, 0, cs[-1]) + cs[index1+1]-cs[index0] 
+0

真的很緊湊,比我想象的要好,做得好! – Divakar

+0

哇,很好地完成!謝謝! – Fnord