Skip to main content
 首页 » 编程设计

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

2025年05月04日20落叶无声

我有以下数组:

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]]]) 

我已经试过了,但它没有返回:

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)) 

否则你可以使用对象方法得到相同的结果,像这样:

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

注意第一个返回 ndarray 而最后一个返回 None 因为它改变了对象本身。有关详细信息,请查看 numpy.resize doc