将此 (4,4) numpy ndarray 重塑为 (2,2,4) ndarray

Reshape this (4,4) numpy ndarray to (2,2,4) ndarray

我有这个 numpy ndarray nd,形状为 (4,4)

[
    [1.07 1.16 1.00 1.11]
    [1.13 1.19 1.11 1.17]
    [1.17 1.17 1.13 1.16]
    [1.14 1.16 1.03 1.04]
]

我想将它重塑为 ndarray 到 (2,2,4),它应该看起来像这样。

[
    [
        [1.07 1.16 1.00 1.11]
        [1.13 1.19 1.11 1.17]
    ]
    [
        [1.17 1.17 1.13 1.16]
        [1.14 1.16 1.03 1.04]
    ]
]

我正在使用 python v3.6

你可以使用 reshape:

import numpy as np
nd = np.array([
    [1.07, 1.16, 1.00, 1.11],
    [1.13, 1.19, 1.11, 1.17],
    [1.17, 1.17, 1.13, 1.16],
    [1.14, 1.16, 1.03, 1.04]])

nd_new = np.reshape(nd, (2,2,4))