'How to reshape a K-by-M*N 2d array to N-by-M-by-K 3d array in Numpy

I have a 2d array of shape (K,M*N). I would like to have a 3d array of shape (M,K,N).

The example I am working on with is: K=2,M=4,N=3

z = np.array([[1, 3, 5, 7, 1, 3, 5, 7, 1, 0, 1, 1],
              [2, 4, 6, 8, 2, 4, 6, 8, 2, 3, 4, 5]])

z can be seen as a block matrix that contains 4 matrices of shape (2,3). So, I would like to get:

s = np.array([[[1, 3, 5], 
               [2, 4, 6]],
               
               [[7, 1, 3],
                [8, 2, 4]],
              
               [[5, 7, 1], 
                [6, 8 ,2]],

               [[0, 1, 1],
                [3, 4, 5]]])

I tried with np.reshape(z, (4,2,3)). But it does not seem to work. I tired to change the order=A,F,C of the reshape function but the answer is always wrong.

Any solution using Numpy?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source