2016-08-15 51 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