Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: add a vector to matrix column wise

Tags:

python

numpy

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?

like image 557
Sounak Avatar asked Jul 23 '15 12:07

Sounak


1 Answers

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

like image 68
unutbu Avatar answered Oct 10 '22 09:10

unutbu