2014-01-09 27 views
1

我有問題要添加一個子陣列到現有的二維數組。 我其實是新來的numpy和python,來自MATLAB這是一件小事做。 請注意,通常情況下,a是我的問題中的一個大矩陣。如何使用numpy在現有2D數組中添加2D子數組?

import numpy as np 

a = np.array(arange(16)).reshape(4,4) # The initial array 
b = np.array(arange(4)).reshape(2,2) # The subarray to add to the initial array 
ind = [0,3] # The rows and columns to add the 2x2 subarray 

a[ind][:,ind] += b #Doesn't work although does not give an error 

我看了看周圍,以下可以工作

a[:4:3,:4:3] += b 

,但我怎麼可以定義IND事先? 此外,如何定義ind是否包含兩個以上不能用跨度表示的數字?例如IND = [1,15,34,67]

+1

只是爲了解釋爲什麼'一個[IND] [:, IND] + = b'不起作用,這是因爲'a [ind]'(其中'ind'是一系列座標)複製。因此,它可以工作,但'+ ='應用於未保存的副本。 'a'不變。基本上,這是因爲你有兩次使用「花哨」的索引。 @ DSM的答案將它結合成一個「花哨」的索引表達式,所以'+ ='按預期工作。另一種寫法是'a [ind [:,None],ind [None,:]] + = b',但這需要'ind'是一個numpy數組而不是一個列表。 –

回答

4

一個來處理一般情況下是使用方式np.ix_

>>> a = np.zeros((4,4)) 
>>> b = np.arange(4).reshape(2,2)+1 
>>> ind = [0,3] 
>>> np.ix_(ind, ind) 
(array([[0], 
     [3]]), array([[0, 3]])) 
>>> a[np.ix_(ind, ind)] += b 
>>> a 
array([[ 1., 0., 0., 2.], 
     [ 0., 0., 0., 0.], 
     [ 0., 0., 0., 0.], 
     [ 3., 0., 0., 4.]])