Alex Alex - 3 months ago 19
Python Question

Reshaping a numpy array (matrix) where elements appear in order

I have a numpy array with the following shape:

shape -> data
5x3 -> [[
12 10 33
9 88 41
13 39 27
1 4 7
65 78 13
]]


I need the numpy array to look like this though:

shape -> data
5x3 -> [[
12 41 4
10 13 7
33 39 65
9 27 78
88 1 13
]]


Essentially, given a numpy array X, I want to create a new array, Y with the same shape as X that takes all the values (left -> right) in each column of X and then puts those values in the same order, but by row.

I have a feeling this might be a simple or easy thing to do with reshape, but I haven't been able to find out if its doable.

Answer

It's a simple enough procedure. We just need to perform two phases, a reshape and a transpose:

Y = X.reshape(X.shape[::-1]).T