您正在寻找np.add.at
。因此,假设X
是1D
阵列,其中所述添加是要被存储,并且将被添加A
阵列保持的索引和值,可以执行 -
np.add.at(X,A[:,0],A[:,1])
因此,输入是:
X : Array holding the additions
A[:,0] : Indices where additions are to be stored
A[:,1] : Values to be added
采样运行 -
In [21]: A = np.array([[5,20],[8,10]]) # Indices and values
In [22]: X = np.zeros(10,dtype=A.dtype) # Array to store additions
In [23]: np.add.at(X,A[:,0],A[:,1]) # Perform np.add.at
In [24]: X # Show output
Out[24]: array([ 0, 0, 0, 0, 0, 20, 0, 0, 10, 0])
如果 “添加”,哟你的意思是索引是唯一的,你只是想要“放”数值,而不是“增加”,你可以初始化输出数组和索引到它里面,就像这样一个样例 -
In [25]: A = np.array([[5,20],[8,10]])
In [26]: X = np.zeros(10,dtype=A.dtype)
In [27]: X[A[:,0]] = A[:,1]
In [28]: X
Out[28]: array([ 0, 0, 0, 0, 0, 20, 0, 0, 10, 0])