[SOLVED] How do I reshape a NumPy multi dimensional array to another array with the same dimensions, but different shape?

Issue

I have a NumPy multi dimensional array of shape (1,76,76,255). I want to reshape it to another multidimensional array of shape (1,255,76,76). It’s still a 4D array, but I need to change the data indices I guess.

Is there an easy way without using loops?

Solution

The function you are looking for is np.moveaxis() which lets you move a source axis to its destination.

>>> arr = np.random.random((1,76,76,255))
>>> 
>>> arr.shape
(1, 76, 76, 255)
>>> arr2 = np.moveaxis(arr, 3, 1)
>>> arr2.shape
(1, 255, 76, 76)
>>> 

Please note that these axes are 0-indexed

Answered By – tbhaxor

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *