【问题标题】:Concatenate several different shape matrices into one, padding zeroes将几个不同的形状矩阵连接成一个,填充零
【发布时间】:2026-02-13 04:55:01
【问题描述】:
a = [[1, 2, 3, 4]]
b = [[1, 2, 3, 4], [1, 2, 3, 4]]
c = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]

如何将 a、b 和 c 连接成一个矩阵? 如果形状不匹配,如上所示,填充零以使其匹配。

在这种情况下:

a.shape => (1, 4)
b.shape => (2, 4)
c.shape => (1, 3, 3)

我想要的输出形状应该是:(2, 4, 3),因为它是最大的维度。

【问题讨论】:

  • 您必须选择所需的结果形状和布局。我看到(1,4),(2,4)和(1,3,3)。没有明显的共同形状。 concatenate 对匹配尺寸有一些有据可查的要求。
  • 我想使用最大的维度进行连接。即 (2, 4, 3)。裸连接有可能吗? @hpaulj
  • 创建一个该大小的zeros 数组,并将数组复制到所需的切片。

标签: python python-3.x numpy


【解决方案1】:
In [125]: a = [[1, 2, 3, 4]]
     ...: b = [[1, 2, 3, 4], [1, 2, 3, 4]]
     ...: c = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]

你想要的结果数组:

In [126]: res = np.zeros((2,4,3), int)

现在让我们赋值:

要将 (1,4) a 分配给我们必须使用的数组:

In [128]: res[[0],:,0] = a

b:

In [129]: res[:,:,0] = b

但是我认为这会覆盖部分或全部a

c:

In [131]: res[[1],:3,:] = c

结果:

In [132]: res
Out[132]: 
array([[[1, 0, 0],
        [2, 0, 0],
        [3, 0, 0],
        [4, 0, 0]],

       [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
        [4, 0, 0]]])

我可以在第二层看到c 块。在第一个平面上我看到a,或者它是b 的第一“行”。在第二个平面上,我看到了b 的一部分,但其余部分已被c 覆盖。

这里有一个更好的安装块的方法:

In [141]: res = np.zeros((2,4,3), int)
In [142]: res[[1],:3,:] = c
In [143]: res[[0],:,0] = np.array(a)*10
In [144]: res[0,:,1:] = np.array(b).T*100
In [145]: res
Out[145]: 
array([[[ 10, 100, 100],
        [ 20, 200, 200],
        [ 30, 300, 300],
        [ 40, 400, 400]],

       [[  1,   2,   3],
        [  4,   5,   6],
        [  7,   8,   9],
        [  0,   0,   0]]])

但通常当我们连接数组时,我们会在其“自己的”维度上放置一个新数组,

例如从 3 个平面开始,3 个输入各一个:

In [146]: res = np.zeros((3,3,4), int)
In [147]: res[0,0,:] = np.array(a)*10
In [148]: res[1,:2,:] = np.array(b)*100
In [149]: res[[2],:3,:3] = np.array(c)
In [150]: res
Out[150]: 
array([[[ 10,  20,  30,  40],
        [  0,   0,   0,   0],
        [  0,   0,   0,   0]],

       [[100, 200, 300, 400],
        [100, 200, 300, 400],
        [  0,   0,   0,   0]],

       [[  1,   2,   3,   0],
        [  4,   5,   6,   0],
        [  7,   8,   9,   0]]])

正如最初评论的那样,对于这种混合形状,没有一个单一的、明显的布局。

【讨论】:

    【解决方案2】:

    这是一种将每个向量扩展到所需形状然后将它们连接起来的方法:

    a = np.array([[1, 2, 3, 4]])
    b = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])
    c = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
    
    # New dimensions:
    len1 = 2
    len2 = 4
    len3 = 3
    
    # Resize and reshape all vectors to match new dims
    # .reshape() pads zeros to array in place 
    a.resize(len1*len2*len3)
    new_a = a.reshape(len1,len2,len3)
    b.resize(len1*len2*len3)
    new_b = b.reshape(len1,len2,len3)
    c.resize(len1*len2*len3)
    new_c = c.reshape(len1,len2,len3)
    
    print(new_a) 
    print(new_a.shape) # output: (2, 4, 3)
    print(new_a.shape == new_b.shape == new_c.shape == (len1, len2, len3)) # output: True
    
    new_arr = np.concatenate([new_a, new_b, new_c])
    print(new_arr)
    

    【讨论】: