2011-02-01 25 views
1

假設您有一個數組(m,m)並且想要使它成爲(n,n)。例如,將2x2矩陣轉換爲6x6。所以:Python:將尺寸添加到二維數組

[[ 1. 2.] 
[ 3. 4.]] 

要:

[[ 1. 2. 0. 0. 0. 0.] 
[ 3. 4. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.]] 

這是我在做什麼:

def array_append(old_array, new_shape): 
    old_shape = old_array.shape 
    dif = np.array(new_shape) - np.array(old_array.shape) 
    rows = [] 
    for i in xrange(dif[0]): 
     rows.append(np.zeros((old_array.shape[0])).tolist()) 
    new_array = np.append(old_array, rows, axis=0) 
    columns = [] 
    for i in xrange(len(new_array)): 
     columns.append(np.zeros(dif[1]).tolist()) 
    return np.append(new_array, columns, axis=1) 

使用例:

test1 = np.ones((2,2)) 
test2 = np.zeros((6,6)) 
print array_append(test1, test2.shape) 

輸出:

[[ 1. 1. 0. 0. 0. 0.] 
[ 1. 1. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.] 
[ 0. 0. 0. 0. 0. 0.]] 

根據this答案。但是對於簡單的操作來說,這是很多代碼。有一個更簡潔/ pythonic的方式來做到這一點?

+0

@pnodnda:你的做法是太複雜了。只需分配新陣列並將舊的副本複製到適當的位置即可。就是這麼簡單,正如Benjamins(已修改)和我的回答所證明的那樣。順便說一句,追加單詞通常與動態數據結構相關聯,而`numpy.array`不是。謝謝 – eat 2011-02-01 21:27:08

回答

3

爲什麼不使用array = numpy.zeros((6,6)),看到numpy docs ...

編輯,woops,問題已經被編輯過......我想你正試圖把那些在用零填充陣列的一部分?然後:

array = numpy.zeros((6,6)) 
array[0:2,0:2] = 1 

如果小矩陣不都值1:

array[ystart:yend,xstart:xend] = smallermatrix 
+0

你讀過標題以外的任何東西嗎? – pnodbnda 2011-02-01 21:06:47

1

這將是那麼:

# test1= np.ones((2, 2)) 
test1= np.random.randn((2, 2)) 
test2= np.zeros((6, 6)) 
test2[0: 2, 0: 2]= test1