問(wèn)題描述
假設(shè)您有一個(gè)需要相加的值數(shù)組
Assume you have an array of values that will need to be summed together
d = [1,1,1,1,1]
第二個(gè)數(shù)組指定哪些元素需要相加
and a second array specifying which elements need to be summed together
i = [0,0,1,2,2]
結(jié)果將存儲(chǔ)在大小為 max(i)+1
的新數(shù)組中.因此,例如 i=[0,0,0,0,0]
相當(dāng)于將 d
的所有元素相加并將結(jié)果存儲(chǔ)在位置 0
的大小為 1
的新數(shù)組.
The result will be stored in a new array of size max(i)+1
. So for example i=[0,0,0,0,0]
would be equivalent to summing all the elements of d
and storing the result at position 0
of a new array of size 1
.
我嘗試使用
c = zeros(max(i)+1)
c[i] += d
但是,+=
操作只將每個(gè)元素添加一次,從而給出了
However, the +=
operation adds each element only once, thus giving the unexpected result of
[1,1,1]
而不是
[2,1,2]
如何正確實(shí)現(xiàn)這種求和?
How would one correctly implement this kind of summation?
推薦答案
這個(gè)解決方案對(duì)于大型數(shù)組應(yīng)該更有效(它迭代可能的索引值而不是 i
的單個(gè)條目):
This solution should be more efficient for large arrays (it iterates over the possible index values instead of the individual entries of i
):
import numpy as np
i = np.array([0,0,1,2,2])
d = np.array([0,1,2,3,4])
i_max = i.max()
c = np.empty(i_max+1)
for j in range(i_max+1):
c[j] = d[i==j].sum()
print c
[1. 2. 7.]
這篇關(guān)于按索引對(duì)numpy數(shù)組的累積求和的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!