Fomalhaut
Fomalhaut

Reputation: 9745

How to sum 2d and 1d arrays in numpy?

Supposing I have 2d and 1d numpy array. I want to add the second array to each subarray of the first one and to get a new 2d array as the result.

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> b = np.array([2, 3])
>>> c = ... # <-- What should be here?
>>> c
array([[3, 5],
       [5, 7],
       [7, 9],
       [9, 22]])

I could use a loop but I think there're standard ways to do it within numpy.

What is the best and quickest way to do it? Performance matters.

Thanks.

Upvotes: 2

Views: 2986

Answers (1)

user2261062
user2261062

Reputation:

I think the comments are missing the explanation of why a+b works. It's called broadcasting

Basically if you have a NxM matrix and a Nx1 vector, you can directly use the + operator to "add the vector to each row of the matrix.

This also works if you have a 1xM vector and want to add it columnwise.

Broadcasting also works with other operators and other Matrix dimensions.

Take a look at the documentation to fully understand broadcasting

Upvotes: 2

Related Questions