Home > front end >  Reshape 5D array to 2D array
Reshape 5D array to 2D array

Time:10-12

I have an array with this shape (26, 396, 1, 1, 6) which I want to convert into this shape (10296, 6) meaning that I want to stack the 396 arrays on top of each other.

I tried:

a = b.reshape(26*396,6)

but this does not "stack" them correctly. I want (1, 396, 1, 1, 6) to be the first 396 arrays of the new array, (2, 396, 1, 1, 6) to be the next 396 arrays of the array, (3, 396, 1, 1, 6) the next and so on.

CodePudding user response:

I believe what you are looking for is to concatenate the second axis down using np.concatenate:

>>> np.concatenate(x, 1).reshape(-1, 6)

Alternatively, you can use np.hstack:

>>> np.hstack(x).reshape(-1, 6)

Alternatively, as noted by @Yann Ziselman in the comments, you can swap the first two axes before reshaping to the final form:

x.swapaxes(0,1).reshape(-1, 6)

Here is a minimal example:

>>> x = np.random.rand(3, 4, 1, 1, 3)
array([[[[[0.66762863, 0.67280411, 0.8053661 ]]],


        [[[0.55051478, 0.79648146, 0.66660467]]]],



       [[[[0.58070253, 0.76738551, 0.30835528]]],


        [[[0.10904043, 0.13234366, 0.25146988]]]]])


>>> np.hstack(x).reshape(-1, 3)
array([[0.66762863, 0.67280411, 0.8053661 ],
       [0.58070253, 0.76738551, 0.30835528],
       [0.55051478, 0.79648146, 0.66660467],
       [0.10904043, 0.13234366, 0.25146988]])

>>> np.reshape(-1, 3) # compared to flattening operation
array([[0.66762863, 0.67280411, 0.8053661 ],
       [0.55051478, 0.79648146, 0.66660467],
       [0.58070253, 0.76738551, 0.30835528],
       [0.10904043, 0.13234366, 0.25146988]])
  • Related