Aizzaac
Aizzaac

Reputation: 3318

Multiple 3D arrays to one 2D array

I have many 3D arrays in different files. I want to turn them into 2D arrays and then join them in 1 array. I managed to get the 2D array, but not the format. Ex: Original 3D array of (4x2x2):

    [[[ 0  1]
      [ 2  3]]

     [[ 4  5]
      [ 6  7]]

     [[ 8  9]
      [10 11]]

     [[12 13]
      [14 15]]]

I want it to become 2D (2x8):

    [[0 1 4 5  8  9 12 13]
     [2 3 6 7 10 11 14 15]]

This is my code:

    import numpy as np
    x=np.arange(16).reshape((4,2,2)) #Depth, Row, Column
    y=x.reshape((x.shape[1], -1), order='F')

If there is a better way to do this, please feel free to improve my code.

Upvotes: 2

Views: 108

Answers (1)

Divakar
Divakar

Reputation: 221514

You can use np.swapaxes to swap the first two axes and then reshape, like so -

y = x.swapaxes(0,1).reshape(x.shape[1],-1)

Upvotes: 3

Related Questions