Python:向二维数组添加维度

1 投票
2 回答
583 浏览
提问于 2025-04-16 11:02

假设你有一个数组,大小是(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.]]

这个内容是基于这个回答的。不过我觉得这段代码有点多,做这样一个简单的操作是不是有更简洁、更符合Python风格的方法呢?

2 个回答

1

那样的话就是:

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

为什么不使用 array = numpy.zeros((6,6)) 呢?可以查看一下 numpy 的文档...

编辑:哎呀,问题被修改了... 我猜你是想在一个全是零的数组里放一些一?那么:

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

如果这个小矩阵并不是全部都是1:

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

撰写回答