Python - 将 3D numpy 数组转换为 2D

数据挖掘 Python 麻木的
2021-09-15 10:49:18

我有一个像这样的 3D 矩阵:

array([[[ 0,  1],
      [ 2,  3]],

      [[ 4,  5],
      [ 6,  7]],

      [[ 8,  9],
      [10, 11]],

      [[12, 13],
      [14, 15]]])

并希望以网格格式堆叠它们,最终得到:

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

目前,我正在使用 numpy 作为库。

2个回答

我建议您也访问此链接 ,因为这种情况也可以使用 np.reshape((-1,2))

允许您以numpy.reshape()多种方式进行重塑。

它通常逐行解开数组,然后按照您想要的方式重塑。

如果您希望它按列顺序解开数组,您需要使用参数order='F'

假设数组是a. 对于上述情况,您有一个(4, 2, 2) ndarray

numpy.reshape(a, (8, 2))将工作。

在一般情况下(l, m, n) ndarray:

numpy.reshape(a, (l*m, n))应该使用。

或者,numpy.reshape(a, (a.shape[0]*a.shape[1], a.shape[2]))应该使用。

有关更多信息numpy.reshape()