简体   繁体   中英

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?

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] 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 (ie along its rows) to be broadcasted.

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 (ie along its columns) to be broadcasted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM