【问题标题】:Iterating through two arrays with a correlation and getting the sum Numpy Python遍历两个具有相关性的数组并获得总和 Numpy Python
【发布时间】:2021-06-05 09:31:57
【问题描述】:

我正在尝试修改下面的代码,以便将与之相关的 indexesNumbers 值相加。

因此,由于indexes 中的第一个元素是 3,因此它取 Numbers 中的前 3 个元素,即 1, 5, 6 所有这些整数的总和等于 12。

接下来 5 个元素中的第二个值正在计算 7,4,3,6,7,它等于 27。

我正在尝试实现Expected Output,但我得到了Current Output,我可以在代码中更改什么以实现Expected Output,而无需使用for循环。

Numbers = np.array([1, 5, 6,7,4,3,6,7,11,3,4,6,2,20])
indexes = np.array([3 , 5, 5])
np.add.reduceat(Numbers, indexes)

电流输出:

array([11,  3, 62])

预期输出

array([12, 27, 26])

【问题讨论】:

    标签: python arrays function numpy iteration


    【解决方案1】:
    np.add.reduceat(Numbers, [0,3,3,8,8,13])[::2]
    

    【讨论】:

      【解决方案2】:

      按累计和配对索引,然后提供给reduceat

      pair_indexes = np.insert(
          indexes.cumsum(), 0, 0
      ).repeat([1] + [2] * (len(indexes) - 1) + [1])
      
      np.add.reduceat(Numbers, pair_indexes)[::2]
      

      【讨论】:

        【解决方案3】:

        调整您的“索引”变量以表示 bin 而不是增量。

        Numbers = np.array([1, 5, 6,7,4,3,6,7,11,3,4,6,2,20])
        indexes = np.array([0, 3 , 8, 13])
        
        answ = np.add.reduceat(Numbers, indexes)[:-1]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-05
          • 2018-04-22
          • 1970-01-01
          • 2021-05-06
          • 2017-04-08
          • 1970-01-01
          相关资源
          最近更新 更多