【问题标题】:Concatenating 3D arrays with different dimensions on axis 2在轴 2 上连接具有不同维度的 3D 数组
【发布时间】:2021-04-02 08:18:56
【问题描述】:

我正在尝试将前两个维度上大小相同但第三个维度上大小不同的多个 3D 数组放在一起。我正在使用 numpy.hstack()。

    import numpy as np
    first = np.array([[[1,2], [3,4]],
                      [[5,6], [7,8]],
                      [[9,10],[11,12]]])
    second = np.array([[[88],[88]],
                      [[88],[88]],
                      [[88],[88]]])
    output = np.hstack((first,second))
    print (output)

这会导致错误:

发生异常:ValueError 连接轴的所有输入数组维度必须完全匹配,但沿着维度 2,索引 0 处的数组大小为 2,索引 1 处的数组大小为 1 连接轴的所有输入数组维度必须完全匹配,但沿着维度2,索引 0 处的数组大小为 2,索引 1 处的数组大小为 1

现在,如果我在第二维不匹配的两个二维数组上尝试这个,np.hstack() 没有问题。例如:

    import numpy as np
    
    first= np.array([[1,2],[3,4],[5,6]])
    second= np.array([[88],[88],[88]])
    output = np.hstack((first,second))
    print (output)

按预期输出:

    [[ 1  2 88]
     [ 3  4 88]
     [ 5  6 88]]

我想要使用 3D 连接的结果是:

    [[[ 1  2 88],[ 3  4 88]]
     [[ 5  6 88],[ 7  8 88]]
     [[ 9  10 88],[ 11  12 88]]]

我的做法是否正确?有替代方案吗?感谢您的帮助。

【问题讨论】:

  • np.hstack 表示它在 第二轴 上连接。你想要最后一个,第三个。

标签: python-3.x numpy


【解决方案1】:

np.concatenate 就是你要找的东西:

>>> import numpy as np
>>> first = np.arange(1, 13).reshape(3, 2, 2); first
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]]])
>>> second = np.repeat(88, 6).reshape(3, 2, 1); second
array([[[88],
        [88]],

       [[88],
        [88]],

       [[88],
        [88]]])
>>> np.concatenate((first, second), axis=2)
array([[[ 1,  2, 88],
        [ 3,  4, 88]],

       [[ 5,  6, 88],
        [ 7,  8, 88]],

       [[ 9, 10, 88],
        [11, 12, 88]]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 2022-01-25
    • 2021-12-05
    • 2021-04-04
    • 1970-01-01
    • 2020-08-24
    • 2021-05-02
    相关资源
    最近更新 更多