本文介紹了索引對之間子數(shù)組中值的 Numpy 總和的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
假設(shè)我有一個數(shù)組 A.我有一系列索引對 (a1, b1), (a2, b2) ... (an, bn)
Suppose I have an array A. I have a series of index pairs (a1, b1), (a2, b2) ... (an, bn)
我想獲得這些對之間元素的所有總和.即
I want to obtain all the sums of the elements between those pairs. i.e.
sum(A[a1:b1]), sum(A[a2:b2]), sum(A[a3:b3]) ...
就運行時而言,最有效的方法是什么?
In terms of run-time, what's the most efficient way of doing this?
謝謝!
推薦答案
假設(shè)您的索引對存儲在形狀為 (n, 2)
的 NumPy 數(shù)組 indices
和n
相當大,最好避免任何 Python 循環(huán):
Assuming your index pairs are stored in a NumPy array indices
of shape (n, 2)
and n
is fairly large, it is probably best to avoid any Python loop:
c = numpy.r_[0, A.cumsum()][indices]
sums = c[:,1] - c[:,0]
這篇關(guān)于索引對之間子數(shù)組中值的 Numpy 總和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!