tia*_*ong 5 python numpy array-broadcasting
我想将矩阵的每一列添加到 numpy 数组,但numpy.broadcast只允许将矩阵的每一行添加到数组。我怎样才能做到这一点?
我的想法是首先转置矩阵,然后将其添加到数组中,然后转置回来,但这使用了两次转置。有没有一个函数可以直接实现呢?
您可以使用仅包含一列的第二个矩阵,而不是使用数组:
matrix = np.matrix(np.zeros((3,3)))
array = np.matrix([[1],[2],[3]])
matrix([[1],
[2],
[3]])
matrix + array
matrix([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
Run Code Online (Sandbox Code Playgroud)
如果你原来有一个数组,你可以像这样重塑它:
a = np.asarray([1,2,3])
matrix + np.reshape(a, (3,1))
matrix([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
Run Code Online (Sandbox Code Playgroud)