0

I have a 2D numpy array of 3n rows and m columns. How do I reshape it into a 3D numpy array of n rows m columns and 3 slices along the 3rd dimension.

2D to 3D transformation rowise

zoulzubazz
  • 183
  • 8

1 Answers1

0

Ok, here is the one solution. I am sure there are other ways to do it.

import numpy as np
#Generate 24 element 1D array and reshape to 6 rows and 4 columns
a_Array = np.arange(24).reshape(6, 4)
#reshape to distribute data along axis 2 then axis 1 and then axis 0 in order, 
#this is what numpy reshape does by default
a_Array.reshape(2,3,4)
#Swap axes 1 and 2
a_Array.reshape(2,3,4).swapaxes(1,2)
#Transpose to arrange data with data distributed along axis 1
a_Array.reshape(2,3,4).swapaxes(1,2).T

enter image description here

Transpose Visualisation

Link 1 helped understand arrays in multi-dimensions in general. Link 2 was used to generate visual attached as the picture.

zoulzubazz
  • 183
  • 8