【问题标题】:Numpy sum of values between arrays of indices with a wraparound condition具有环绕条件的索引数组之间的数值总和
【发布时间】: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 是的。 index0index1 也可以表示为单个对列表,例如:index = np.array([[0,4],[3,6],...])... 如果有帮助的话。

标签: python arrays numpy


【解决方案1】:

那又怎样:

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

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 2018-07-15
    • 2020-06-27
    • 1970-01-01
    • 2019-04-08
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多