Numpy: add vector to matrix column

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 the addition of a string. How to add them to columns to get

In [65]: result
Out[65]: 
array([[ 7,  8],
       [11, 12]])

I do not want to rearrange the entire array, add and transfer back. Is there another way?

+4
source share
1 answer

Add a new pointer to the end a[:,-1]so that it has a shape (2,1). Adding with bthen broadcast along the column (second axis) instead of rows (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][:, np.newaxis] (2,1). (2,2) 1 ( ), .

+6

Source: https://habr.com/ru/post/1599309/


All Articles