1

In R, I can easily add a smaller vector to a larger vector (assuming length of larger vector is a multiple of length of smaller vector)

a <- seq(1,10,1)
# [1]  1  2  3  4  5  6  7  8  9 10
b <- seq(1,2,1)
# [1] 1 2
a+b
# [1]  2  4  4  6  6  8  8 10 10 12

Is there an easy way to do this in Python?

import numpy as np
a = np.arange(1, 10)
# array([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = np.arange(1,4)
# array([1, 2, 3])

What I tried

a + b?
np.add(a, b)?

1 Answer 1

4

NumPy does not simply assume that you might want to repeat b before adding it to a, you must tell it to do that yourself.

The system by which you can do that is called broadcasting. You create a 2D array by adding another axis of exactly the same length of b. Adding b to that 2D array has exactly the desired behaviour.

And afterwards we flatten the array back to 1D.

(a.reshape(-1, len(b)) + b).ravel()
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, sorry, my example code contained a typo. Will accept your answer when it allows me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.