Home > OS >  How to reshape numpy arrays to turn rows into columns
How to reshape numpy arrays to turn rows into columns

Time:11-17

Lets say I've got the following numpy array of shape 3x3x2:

import numpy as np
X,Y = np.arange(3),np.arange(3)
xy = np.array([[(x, y) for x in X] for y in Y])

The array xy above is given by the following:

[[[0 0]
  [1 0]
  [2 0]]

 [[0 1]
  [1 1]
  [2 1]]

 [[0 2]
  [1 2]
  [2 2]]]

How would I reshape the above array into the following

xy_reshaped = 
[[0 1 2 0 1 2 0 1 2],
[0 0 0 1 1 1 2 2 2]]

I believe I am trying to turn the previous arrays rows into the new arrays columns. However Ive also lost an axis as the new array is of shape xy_reshaped.shape = (2,9) (there is no 3rd axis like there was in the original array).

np.reshape can only be set to read elements row wise and column wise, both orderings do not work for the above case.

Is there a simple solution to do the reshaping?

CodePudding user response:

Do the obvious reshape:

In [304]: xy.reshape(9,2)
Out[304]: 
array([[0, 0],
       [1, 0],
       [2, 0],
       [0, 1],
       [1, 1],
       [2, 1],
       [0, 2],
       [1, 2],
       [2, 2]])

now just transpose:

In [305]: xy.reshape(9,2).transpose()
Out[305]: 
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [0, 0, 0, 1, 1, 1, 2, 2, 2]])

There are other ways of doing this, but this is most obvious and easy to understand.

  • Related