numpy:将向量添加到矩阵列明智 [英] Numpy: add a vector to matrix column wise
问题描述
a
Out[57]:
array([[1, 2],
[3, 4]])
b
Out[58]:
array([[5, 6],
[7, 8]])
In[63]: a[:,-1] + b
Out[63]:
array([[ 7, 10],
[ 9, 12]])
这是逐行加法.我如何将它们按列明智地添加以获得
This is row wise addition. How do I add them column wise to get
In [65]: result
Out[65]:
array([[ 7, 8],
[11, 12]])
我不想转置整个数组,添加然后转回.还有其他办法吗?
I don't want to transpose the whole array, add and then transpose back. Is there any other way?
推荐答案
在a[:,-1]
的末尾添加新轴,使其形状为(2,1)
.然后,添加b
将会沿着列(广播 第二个轴)而不是行(这是默认值).
Add a newaxis to the end of a[:,-1]
, so that it has shape (2,1)
. Addition with b
would then broadcast along the column (the second axis) instead of the rows (which is the default).
In [47]: b + a[:,-1][:, np.newaxis]
Out[47]:
array([[ 7, 8],
[11, 12]])
a[:,-1]
具有形状(2,)
. b
具有形状(2,2)
.广播默认情况下会在左侧的 中添加新的坐标轴.因此,当NumPy计算a[:,-1] + b
时,其广播机制会导致a[:,-1]
的形状更改为(1,2)
并广播为(2,2)
,并沿其长度1轴(即沿其行)的值进行广播.
a[:,-1]
has shape (2,)
. b
has shape (2,2)
. Broadcasting adds new axes on the left by default. So when NumPy computes a[:,-1] + b
its broadcasting mechanism causes a[:,-1]
's shape to be changed to (1,2)
and broadcasted to (2,2)
, with the values along its axis of length 1 (i.e. along its rows) to be broadcasted.
相反,a[:,-1][:, np.newaxis]
具有形状(2,1)
.因此,广播将其形状更改为(2,2)
,并沿其长度为1的轴(即沿其列)的值进行广播.
In contrast, a[:,-1][:, np.newaxis]
has shape (2,1)
. So broadcasting changes its shape to (2,2)
with the values along its axis of length 1 (i.e. along its columns) to be broadcasted.
这篇关于numpy:将向量添加到矩阵列明智的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!