Numpy 将 2D 重塑为 3D:将列移动到 "depth"

Numpy reshaping 2D to 3D: moving columns to "depth"

问题

如何将 2D 矩阵重塑为移动列的 3D 矩阵 "depth-wise"?

我希望数组 a 看起来像数组 b

import numpy as np

a = np.array([
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
            ])

b = np.array([
                [[1,1,1,1,1,1], 
                 [1,1,1,1,1,1], 
                 [1,1,1,1,1,1], 
                 [1,1,1,1,1,1]],
                [[2,2,2,2,2,2], 
                 [2,2,2,2,2,2], 
                 [2,2,2,2,2,2], 
                 [2,2,2,2,2,2]],
                [[3,3,3,3,3,3], 
                 [3,3,3,3,3,3], 
                 [3,3,3,3,3,3], 
                 [3,3,3,3,3,3]],
            ])

我尝试做的事情

结果不是我想要达到的结果

x = np.reshape(a, (a.shape[0], -1, 3))

我还尝试了以下方法: 1)将a分成3组 2) 试图对这些集合进行 dstack 但没有产生想要的结果

b = np.hsplit(a,3)
c = np.dstack([b[0],b[1],b[2]])

应该这样做:

import numpy as np

a = np.array([
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3], 
                [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
            ])

b = np.array([
                [[1,1,1,1,1,1],
                 [1,1,1,1,1,1],
                 [1,1,1,1,1,1],
                 [1,1,1,1,1,1]],
                [[2,2,2,2,2,2],
                 [2,2,2,2,2,2],
                 [2,2,2,2,2,2],
                 [2,2,2,2,2,2]],
                [[3,3,3,3,3,3],
                 [3,3,3,3,3,3],
                 [3,3,3,3,3,3],
                 [3,3,3,3,3,3]],
            ])

a_new = np.swapaxes(a.reshape(a.shape[0], 3, -1), 0, 1)

np.array_equal(a_new, b)

-> 正确

你只需要 transposeTreshape

a.T.reshape(3,4,6)

a.T.reshape(b.shape)

Out[246]:
array([[[1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1]],

       [[2, 2, 2, 2, 2, 2],
        [2, 2, 2, 2, 2, 2],
        [2, 2, 2, 2, 2, 2],
        [2, 2, 2, 2, 2, 2]],

       [[3, 3, 3, 3, 3, 3],
        [3, 3, 3, 3, 3, 3],
        [3, 3, 3, 3, 3, 3],
        [3, 3, 3, 3, 3, 3]]])