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.
Asked
Active
Viewed 1,168 times
0
-
1Start with a reshape to (3,n,m). Then if you want `transpose` to (n,m,3). – hpaulj Apr 30 '19 at 20:55
-
https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html – FabienP Apr 30 '19 at 21:00
1 Answers
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
Link 1 helped understand arrays in multi-dimensions in general. Link 2 was used to generate visual attached as the picture.

zoulzubazz
- 183
- 8