Search code examples
rnumpyrecycle

How to recycle elememts when dimensions of two numpy arrays do not matches?


I would like to do something similar to the following R code with numpy, where y is recycled.

R> x=rbind(c(1,2,3), c(4,5,6))
R> y=c(1,2)
R> x/y
     [,1] [,2] [,3]
[1,]    1  2.0    3
[2,]    2  2.5    3

Obviously, the following code does not work with numpy. Does anybody know what is the equivalent python code that works? Thanks.

>>> x=numpy.array([[1,2,3], [4, 5, 6]])
>>> y=numpy.array([1,2])
>>> x/y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2,3) (2,) 

Solution

  • How about

    x=numpy.array([[1,2,3], [4, 5, 6]])
    y=numpy.array([1,2])
    x/y[:, None]
    

    y[:, None] turns the (2,) array to a (2,1) array, thereby allowing broadcast division with x.