将 3D 阵列重塑为 2D 阵列并返回 3D 阵列

Reshape 3D array to 2D array and back to 3D array

我有一个 3D 数组 (n,x,y),我使用以下内容将其转换为 2D 数组 (x*y,n):

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"

我不确定如何从 2D 阵列重建原始 3D 阵列?

原来的3D数组结构是这样的:

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

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

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

定义:

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)

重塑并执行置换变换。

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

进行逆置换变换,重塑回原来的形状。

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

验证:

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