0

Given two 1-d numpy arrays:

>>> a = np.arange(10)
>>> b = np.arange(2)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b
array([0, 1])

How can I add them such that the values of b are added to values of a as if b was repeated five times? This kind of thing is automatic in R but seemingly not in Numpy:

>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (10,) (2,) 

Best I can come up with is to tile b to make it the right size, but this seems clunky (especially the integer division...):

>>> a + np.tile(b, a.shape[0]//b.shape[0])
array([ 0,  2,  2,  4,  4,  6,  6,  8,  8, 10])

assuming the length of b divides the length of a, is there a better solution?

1 Answer 1

1

One alternative solution is to use implicit broadcasting:

(a.reshape(-1, b.shape[0]) + b).reshape(-1)

Note that reshape operations are cheap (there is no copy made). Note that a.shape[0] must still be divisible by b.shape[0] like the tile-based solution.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I thought maybe I'd missed a method in the docs that would do this, given an array, an axis, and another array to repeat it out to. This seems to be optimal though!

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.