Home > Mobile >  Reshape 3D array to 2D array and back to 3D array
Reshape 3D array to 2D array and back to 3D array

Time:04-14

I have a 3D array (n,x,y) that I converted to a 2D array (x*y,n) with the following:

import numpy as np

# Original 3D array (n,x,y)
a = np.arange(24).reshape(3,4,2)
print(a); print(a.shape)enter code here

# Reshape to 2D array (x*y,n)
b = a.reshape(a.shape[0],a.shape[1]*a.shape[2]).T
print(b); print(b.shape)

# Reshape 2D array (x*y,n) to 3D array (n,x,y)
c = "TBA"

I am not sure how I can reconstruct the original 3D array from the 2D array?

The original 3D array has this structure:

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

 [[ 8  9]
  [10 11]
  [12 13]
  [14 15]]

 [[16 17]
  [18 19]
  [20 21]
  [22 23]]]

CodePudding user response:

Define:

perm = np.array([1, 0])
inv_perm = np.empty_like(perm)
inv_perm[perm] = np.arange(perm.size)

a = np.arange(24).reshape(3, 4, 2)

Reshape and perform the permutation transformation.

b = (
    a
    .reshape(a.shape[0], a.shape[1] * a.shape[2])
    .transpose(*perm)
)

Perform the inverse permutation transformation and reshape back to the original shape.

c = (
    b
    .transpose(*inv_perm)
    .reshape(*a.shape)
)

Verify:

>>> (a == c).all()
True
  • Related