Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reshape numpy arrays to turn rows into columns

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading