Boppity Bop
Boppity Bop

Reputation: 10481

Sum vector with matrix in numpy

assume matrix is 2d numpy (MxN) array and vector is 1d array (1xN) - both have same N rows. I need to add to each column in matrix value of same row element in vector:

[[1 2 3],
 [4 5 6]]

[0.1 0.2]

result:

[[1.1 2.1 3.1],
 [4.2 5.2 6.2]]

Upvotes: 3

Views: 2338

Answers (2)

I'mahdi
I'mahdi

Reputation: 24069

you can use numpy.reshape(-1,1) and get what you want:

l1 = np.array([[1, 2, 3],[4, 5 , 6]])

l2 = np.array([0.1, 0.2]).reshape(-1,1)

l1+l2

Output:


array([[1.1, 2.1, 3.1],
       [4.2, 5.2, 6.2]])

Upvotes: 2

akuiper
akuiper

Reputation: 215127

Taking advantage of numpy broadcasting, you can do a + b[:, None]:

a = np.arange(1,7).reshape((2, 3))
b = np.array([0.1, 0.2])

a + b[:, None]
array([[1.1, 2.1, 3.1],
       [4.2, 5.2, 6.2]])

Or:

a + b[:, np.newaxis]
array([[1.1, 2.1, 3.1],
       [4.2, 5.2, 6.2]])

Upvotes: 4

Related Questions