Python 具有环绕条件的索引数组之间的数值之和

Python 具有环绕条件的索引数组之间的数值之和,python,arrays,numpy,Python,Arrays,Numpy,给定一个大的浮点数组和两个索引数组,我正在寻找一种优雅的方法,通过以下规则对给定索引之间包含的所有值求和: 当index1>index0时,求和以直接方式进行 当index1index0时的直接求和 值=np.数组([0,10,20,30,40,50,60,70.])) index0=np.数组([0,3]) index1=np.数组([2,6]) #期望结果:np.数组([30180])#(0+10+20),(30+40+50+60) #index1

给定一个大的浮点数组和两个索引数组,我正在寻找一种优雅的方法,通过以下规则对给定索引之间包含的所有值求和:

  • 当index1>index0时,求和以直接方式进行
  • 当index1
例如:

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导入为np
#index1>index0时的直接求和
值=np.数组([0,10,20,30,40,50,60,70.]))
index0=np.数组([0,3])
index1=np.数组([2,6])
#期望结果:np.数组([30180])#(0+10+20),(30+40+50+60)
#index1
因为我处理的是相当大的阵列,所以如果可能的话,我正在寻找一个优雅的以numpy为中心的解决方案。

那怎么样:

# 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)
cs=np.insert(np.cumsum(值),0,0)
#然后,对于每个索引,以恒定时间获得结果(index0/1大小的线性):
结果=np,其中(index0
你能仔细检查一下你的例子吗,边界和预期结果似乎不一致……这些范围是否有重叠,比如
index0=np.array([0,3])和index1=np.array([4,6])
?@Divakar是的
index0
index1
也可以表示为对的单个列表,例如:
index=np.array([0,4],[3,6],…])
。。。如果有帮助的话。