首页 文章

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

提问于
浏览
2

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

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引发了以下错误:

Big [:,0] = np.reshape(Small,(9,1))ValueError:无法将形状(9,1)的输入数组广播为形状(9)

我也尝试使用flatten,但这也不起作用 . 有没有办法从小矩阵或任何其他方式创建shape(9)数组来处理此错误?

非常感谢您的帮助!

1 回答

  • 1

    尝试:

    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, ) one-dimensional . 您要分配的形状是 (9, 1) 二维 . 你需要通过将双暗调暗 np.reshape(Small, (9,1)) 变成 np.reshape(Small, (9,)) 来协调这一点 . 或者,将one-dim变为双暗 Big[:, 0]Big[:, [0]] . 例外是当我指定'Big [:,0] = Small.reshape((9,1))`时 . 在这种情况下,numpy必须检查 .

相关问题