基于行顺序的 numpy 3D 数组 reshape/flattern 到 1D 数组

numpy 3D array reshape/flattern to 1D array based on row order

我有一个 3D NumPy 数组

x = np.array([[[0, 0, 0, 0],
               [1, 1, 1, 1],
               [2, 2, 2, 2]],

              [[0, 0, 0, 0],
               [1, 1, 1, 1],
               [2, 2, 2, 2]]])

如果我想通过获取 x[0] 的第 n°0 行、x[1] 的第 n°0 行、x[0] 的第 n°1 行,将 3D 数组展平为 1D 数组,x[1] 的第 n°1 行,x[0] 的第 n°2 行,x[1] 的第 n°2 行,并得到以下布局:

[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2]

我怎样才能做到这一点?尝试重塑、压平,none 成功了。

您可以堆叠然后展平阵列:

>>> np.stack(x, axis=1).flatten()
array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2])