Skip to main content
 首页 » 编程设计

python之在 numpy 形状错误中将数组保存在矩阵的列中

2025年04月02日17yxwkf

假设我做了一些计算,并且在循环中每次都得到一个大小为 3 x 3 的矩阵。假设每次,我都想将这样的矩阵保存在一个更大矩阵的列中,该矩阵的行数等于 9(较小矩阵中的元素总数)。首先,我 reshape 较小的矩阵,然后尝试将其保存到大矩阵的一列中。只有一列的简单代码如下所示:

import numpy as np 
Big = np.zeros((9,3)) 
Small = np.random.rand(3,3) 
Big[:,0]= np.reshape(Small,(9,1)) 
print Big 

但是 python 抛出以下错误:

大[:,0]= np.reshape(小,(9,1)) ValueError:无法将输入数组从形状 (9,1) 广播到形状 (9)

我也试过使用 flatten,但也没用。有什么方法可以从小矩阵创建一个 shape(9) 数组或任何其他方法来处理这个错误?

非常感谢您的帮助!

请您参考如下方法:

尝试:

import numpy as np 
Big = np.zeros((9,3)) 
Small = np.random.rand(3,3) 
Big[:,0]= np.reshape(Small,(9,)) 
print Big 

或:

import numpy as np 
Big = np.zeros((9,3)) 
Small = np.random.rand(3,3) 
Big[:,0]= Small.reshape((9,1)) 
print Big 

或:

import numpy as np 
Big = np.zeros((9,3)) 
Small = np.random.rand(3,3) 
Big[:,[0]]= np.reshape(Small,(9,1)) 
print Big 

两种情况都让我明白:

[[ 0.81527817  0.          0.        ] 
 [ 0.4018887   0.          0.        ] 
 [ 0.55423212  0.          0.        ] 
 [ 0.18543227  0.          0.        ] 
 [ 0.3069444   0.          0.        ] 
 [ 0.72315677  0.          0.        ] 
 [ 0.81592963  0.          0.        ] 
 [ 0.63026719  0.          0.        ] 
 [ 0.22529578  0.          0.        ]] 

说明

您尝试分配给 Big 的形状是 (9, ) 一维。您尝试分配的形状是 (9, 1) 二维的。您需要通过将双维 np.reshape(Small, (9,1)) 变成 np.reshape(Small, (9,))< 来协调这一点。或者,将一维的 Big[:, 0] 变成 Big[:, [0]]。异常(exception)是当我分配 'Big[:, 0] = Small.reshape((9,1))` 时。在这种情况下,numpy 必须进行检查。