Home > Software engineering >  Reshaping 3D to 2D in Numpy does not produced intended output
Reshaping 3D to 2D in Numpy does not produced intended output

Time:11-30

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

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))

CodePudding user response:

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
  • Related