Home > Enterprise >  Repeating a shorter Numpy array to a longer array
Repeating a shorter Numpy array to a longer array

Time:11-28

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?

CodePudding user response:

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.

  • Related