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


当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为中心的优雅解决方案。

最佳答案

那个怎么样:

# 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]

关于python - 具有环绕条件的索引数组之间的数值总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38951193/

10-12 07:37