pythonnumpy

3D array to 2D then back again


I have the array

import numpy as np
a = np.array([[[11,12,13], [14,15,16]],
              [[21,22,23], [24,25,26]],
              [[31,32,33], [34,35,36]]])

# array([[[11, 12, 13],
#         [14, 15, 16]],

#        [[21, 22, 23],
#         [24, 25, 26]],

#        [[31, 32, 33],
#         [34, 35, 36]]])

#a.shape
#(3, 2, 3)

I need to reshape it to a 2D array with three columns:

step1 = a.transpose(1, 2, 0).reshape(-1, 3)
# array([[11, 21, 31],
#        [12, 22, 32],
#        [13, 23, 33],
#        [14, 24, 34],
#        [15, 25, 35],
#        [16, 26, 36]])

I then need to reshape it back to the original shape, but I cant figure out how?


Solution

  • You probably could try

    step1 = a.reshape(3,-1).T
    step2 = step1.T.reshape(a.shape)
    
    print(f'step1 :\n {step1}\n')
    print(f'step2 :\n {step2}\n')
    

    and you will see

    step1 :
     [[11 21 31]
     [12 22 32]
     [13 23 33]
     [14 24 34]
     [15 25 35]
     [16 26 36]]
    
    step2 :
     [[[11 12 13]
      [14 15 16]]
    
     [[21 22 23]
      [24 25 26]]
    
     [[31 32 33]
      [34 35 36]]]