Python:将维度附加到二维数组

时间:2011-02-01 21:04:04

标签: python arrays numpy

假设你有一个数组(m,m)并想要它(n,n)。例如,将2x2矩阵转换为6x6矩阵。所以:

[[ 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回答。但这是一个(imho)简单操作的代码。是否有更简洁/ pythonic的方式来做它?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

那就是:

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