简体   繁体   English

迭代两个具有相关性的 arrays 并得到总和 Numpy Python

[英]Iterating through two arrays with a correlation and getting the sum Numpy Python

I am trying to modify the code down below so that it adds up the indexes and the Numbers values that correlate with it.我正在尝试修改下面的代码,以便将与其相关的indexesNumbers值相加。

So since the first element in indexes is 3, it takes the first 3 elements within Numbers which is 1, 5, 6 sum of all these integers is equal to 12.因此,由于indexes中的第一个元素是 3,因此它采用Numbers中的前 3 个元素,即1, 5, 6所有这些整数的总和等于 12。

For the second value in the next 5 elements is being computed 7,4,3,6,7 which is equal to 27.对于接下来 5 个元素中的第二个值,正在计算7,4,3,6,7 ,它等于 27。

I am trying to achieve Expected Output but am getting the Current Output what can I change in the code to achieve the Expected Output without using a for loop.我正在尝试实现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)

Current Output:当前 Output:

array([11,  3, 62])

Expected Output预计 Output

array([12, 27, 26])
np.add.reduceat(Numbers, [0,3,3,8,8,13])[::2]

Pair indices by cumulative sum and then provide it to reduceat通过累积和对索引进行配对,然后将其提供给reduceat

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

np.add.reduceat(Numbers, pair_indexes)[::2]

Adjust your "indexes" variable to represent bins rather than increments.调整您的“索引”变量以表示 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM