2014-01-09 67 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.]])