连接不同维度和形状的 numpy 数组

Join numpy arrays of different dimensions and shapes

我有2个arrays,一个是(2,2)的形状,一个是(2,2,2)的形状。我想将它们堆叠在一起,以便我的最终结果可以具有 (3,2,2) 的形状。我会举例说明我在说什么

Array 1  ->    [ 1,2 ]      -> shape(2,2)
               [ 3,4 ]

Array 2  ->    [ 5,6 ]     [ 9,10  ]     -> shape (2,2,2)
               [ 7,8 ]     [ 11,12 ]
              

Final Array after stacking Arrays 1 and 2  ->  [ 1,2 ]       [ 5,6 ]     [ 9,10  ]    ->shape (3,2,2)
                                               [ 3,4 ]       [ 7,8 ]     [ 11,12 ]

使用 numpy.dstack,沿 depth(第三)轴堆叠阵列:

import numpy as np

a = np.arange(1, 5).reshape(2, 2)
b = np.arange(5, 13).reshape(2, 2, 2)

c = np.dstack((a, b))
print(c)
#[[[ 1  5  6]
#  [ 2  7  8]]
#
# [[ 3  9 10]
#  [ 4 11 12]]]
print(c.shape)
#(2, 2, 3)

编辑:要得到你想要的 (3, 2, 2) 形状,你仍然可以使用 np.dstack,但转置输入和输出:

c = np.dstack((a.T, b.T)).T
print(c)
#[[[ 1  2]
#  [ 3  4]]
#
# [[ 5  6]
#  [ 7  8]]
#
# [[ 9 10]
#  [11 12]]]
print(c.shape)
#(3, 2, 2)

为了更灵活地选择维度,您可以使用 ravelreshape:

import numpy as np
arr1 = np.arange(1, 5).reshape(2, 2)
arr2 = np.arange(5, 13).reshape(2, 2, 2)

stack = np.concatenate((arr1.ravel(),arr2.ravel())).reshape(3,2,2)

输出:

>>> stack
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],
    
       [[ 9, 10],
        [11, 12]]])