2011-02-01 26 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