簡體   English   中英

迭代兩個具有相關性的 arrays 並得到總和 Numpy Python

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

我正在嘗試修改下面的代碼,以便將與其相關的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)

當前 Output:

array([11,  3, 62])

預計 Output

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

通過累積和對索引進行配對,然后將其提供給reduceat

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

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

調整您的“索引”變量以表示 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