2012-11-11 27 views
1

我是一名Python初學者。我想知道是否有一個「好」的方法來做這個操作,而不使用for循環。 考慮的問題numpy中二維數組的選定元素的矢量化賦值語句

u = zeros((4,2)) 
u_pres = array([100,200,300]) 
row_col_index = array([[0,0,2], [0,1,1]]) 

我想分配U [0,0],U [0,1],和u [2,1]分別爲100,200和300。 我想做的形式

u[row_col_index] = u_pres 

的東西如果妳是一維數組這樣的分配工作,但我無法弄清楚如何使這項工作對於二維數組。 你的建議將是最有幫助的。 謝謝

回答

0

你快到了。

你需要的是以下幾點:

u[row_col_index[0], row_col_index[1]] = u_pres 

說明:

既然你說你是在Python初學者(!我太),我想我可能會告訴你這個;它被認爲是unpythonic加載一個模塊,你所做的一切:

#BAD 
from numpy import * 
#GOOD 
from numpy import array #or whatever it is you need 
#GOOD 
import numpy as np #if you need lots of things, this is better 

說明:

In [18]: u = np.zeros(10) 

In [19]: u 
Out[19]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) 

#1D assignment 
In [20]: u[0] = 1 

In [21]: u[1] = 10 

In [22]: u[-1] = 9 #last element 

In [23]: u[-2] = np.pi #second last element 

In [24]: u 
Out[24]: 
array([ 1.  , 10.  , 0.  , 0.  , 
     0.  , 0.  , 0.  , 0.  , 
     3.14159265, 9.  ]) 

In [25]: u.shape 
Out[25]: (10,) 

In [27]: u[9] #calling 
Out[27]: 9.0 

#2D case 
In [28]: y = np.zeros((4,2)) 

In [29]: y 
Out[29]: 
array([[ 0., 0.], 
     [ 0., 0.], 
     [ 0., 0.], 
     [ 0., 0.]]) 

In [30]: y[1] = 10 #this will assign all the second row to be 10 

In [31]: y 
Out[31]: 
array([[ 0., 0.], 
     [ 10., 10.], 
     [ 0., 0.], 
     [ 0., 0.]]) 

In [32]: y[0,1] = 9 #now this is 2D assignment, we use 2 indices! 

In [33]: y[3] = np.pi #all 4th row, similar to y[3,:], ':' means all 

In [34]: y[2,1] #3rd row, 2nd column 
Out[34]: 0.0 


In [36]: y[2,1] = 7 

In [37]: 

In [37]: y 
Out[37]: 
array([[ 0.  , 9.  ], 
     [ 10.  , 10.  ], 
     [ 0.  , 7.  ], 
     [ 3.14159265, 3.14159265]]) 

在你的情況,我們有row_col_indexrow_col_index[0])的第1個數組用於和第二個數組(row_col_index[1])用於列。

最後,如果您不使用ipython,我建議您這樣做,它會幫助您進行學習過程和其他許多事情。

我希望這會有所幫助。

+0

感謝您提供最佳實踐的詳細解答和提示。我一直試圖用row_col_index數組作爲一個整體進行索引而不提取行。 – me10240

+0

不客氣。你能否選擇這個作爲正確的答案。 – pythonista