【问题标题】:Numpy: How to get the sums of integer array slices based on indexes from another array in a vectorized manner?Numpy:如何以矢量化方式根据另一个数组的索引获取整数数组切片的总和?
【发布时间】:2021-10-29 07:14:20
【问题描述】:

给定两个整数数组ab,其中b 中的元素表示a 的索引...

a = array([10,10,10,8,8,8])

b = array([0,2,3,5])

我想生成一个新数组,其元素是a 中元素的总和,沿着b 中给出的索引范围,不包括范围尾部的元素...很难放入的话,但上面给出的ab 的预期结果是:

result = array([0, # sum(a[:0])
                20,  # sum(a[0:2])
                10,  # sum(a[2:3])
                16])  # sum(a[3:5])

我怎样才能以矢量化/“numpythonic”的方式实现这一点?

谢谢!

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    我想你在看np.ufunc.reduceat:

    np.add.reduceat(a,b)
    

    输出:

    # gotta handle the case `b[0] == 0` separately
    array([20, 10, 16,  8])
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      import numpy as np
      
      a = np.array([10,10,10,8,8,8])
      b = np.array([0,2,3,5])
      
      list(map(sum, np.split(a, b)))
      

      它给出:

      [0, 20, 10, 16, 8]
      

      最后一个数字是切片a[5:]的总和。

      【讨论】:

      • 这虽然非常简洁,但并未矢量化。
      【解决方案3】:

      这就是你要找的吗?

      import numpy as np
      
      a = np.array([10,10,10,8,8,8])
      
      b = np.array([0,2,3,5])
      
      result = []
      
      
      for i, v in enumerate(b):
          result.append(sum(a[b[i-1]:v]))
      
      result = np.array(result)
      

      结果:

      [ 0 20 10 16]
      

      【讨论】:

      • 几乎,除了出于性能原因我想避免迭代。在实践中,我的数组要大得多。此外,根据问题中给出的预期结果,结果数组的第一个元素应该为零。不过谢谢!
      猜你喜欢
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 2019-04-15
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多