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

Reshaping 3D to 2D in Numpy does not produced intended output

Given a 3D array as below

nnodes,nslice,nsbj=2,4,3
arr=np.random.randint(10, size=(nsbj,nslice,nnodes))

[[[5 0]
  [3 3]
  [7 9]
  [3 5]]
 [[2 4]
  [7 6]
  [8 8]
  [1 6]]
 [[7 7]
  [8 1]
  [5 9]
  [8 9]]]

I would like to reshape it into an array of shape (2,12)

5   3   7   3   2   7   8   1   7   8   5   8
0   3   9   5   4   6   8   6   7   1   9   9

Using order variation of A,C,F of the reshape does not produced intended output

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

arr.(2,-1,order='F') # tested also against A, and C

Similarly, the following also does not give what I intend

arr.transpose(0,2,1).reshape(2,-1,order='F')

For reproducibility,here is the toy code

import numpy as np
np.random.seed(0)
nnodes,nslice,nsbj=2,4,3
arr=np.random.randint(10, size=(nsbj,nslice,nnodes))

>Solution :

You could ravel/flatten then reshape:

arr.ravel().reshape(2,-1,order='F')

output:

array([[5, 3, 7, 3, 2, 7, 8, 1, 7, 8, 5, 8],
       [0, 3, 9, 5, 4, 6, 8, 6, 7, 1, 9, 9]])

Alternative reshape and transpose:

arr.reshape(-1,2).T
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