【发布时间】:2016-08-15 07:46:03
【问题描述】:
给定一个大的 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 为中心的解决方案。
【问题讨论】:
-
你能仔细检查一下你的例子吗,边界和预期的结果似乎不对......
-
这些范围是否有重叠,例如
index0 = np.array([0,3]) and index1 = np.array([4,6])? -
@Divakar 是的。
index0和index1也可以表示为单个对列表,例如:index = np.array([[0,4],[3,6],...])... 如果有帮助的话。