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 (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With