2016-03-15 90 views
2

我在一個數組中具有形式(索引,值)的元素,例如如何在某些索引中將一個numpy數組中的元素添加到另一個數組中?

5, 20 
8, 10 

我需要將這些元素添加到另一個最初爲空的不同大小的數組中,

X = np.zeros((1, 10)) 

並將X的值設置爲第一個數組中索引處給出的值。所以X,到了最後,應

X = [0, 0, 0, 0, 0, 20, 0, 0, 10, 0] 

由於X的第5個元素應該是20,而第8元素應該是10.是否有一個numpy的陣列功能,這是否,或別的東西,我可以使用爲了快速計算?

回答

1

您正在尋找np.add.at。因此,假設X1D陣列,其中所述添加是要被存儲,並且將被添加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]) 
相關問題