0

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,) 
3
  • Could you explain what's that R code doing?
    – Divakar
    Dec 27, 2017 at 18:59
  • It divides each column of x by y. Dec 27, 2017 at 19:03
  • The title of your question is a bit confusing - what do you mean by "recycling y"?
    – Amos Egel
    Dec 27, 2017 at 19:09

1 Answer 1

1

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.

3

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.