在 Python 中将数组大小调整为另一个形状



我有以下数组:

a = np.random.rand(5,2)
a
array([[0.98736372, 0.07639041],
[0.45342928, 0.4932295 ],
[0.75789786, 0.48546238],
[0.85854235, 0.74868237],
[0.13534155, 0.79317482]])

我想调整它的大小,以便将其分为 2 批,包含三个元素(根据需要添加零):

array([[[0.98736372, 0.07639041],
[0.45342928, 0.4932295 ],
[0.75789786, 0.48546238]],
[[0.85854235, 0.74868237],
[0.13534155, 0.79317482],
[0, 0]]])

我已经尝试过这个,但它返回 None:

a = a.copy()
a.resize((2,3,2), refcheck = False)

我相信 .reshape 不会提供解决方案,因为它无法用 0 填充以符合数组所需的尺寸。

使用numpy.resize,你必须像这样使用:

import numpy as np
a = np.random.rand(5,2)
b = np.resize(a, (2,3,2))

否则,您可以使用 Object 方法来获得相同的结果,如下所示:

import numpy as np
a = np.random.rand(5,2)
a.np.resize(2,3,2)
b = a.copy()

注意 第一个返回ndarray最后一个返回 None,因为它更改了对象本身。有关更多信息,请查看 numpy.resize 文档

最新更新