1

I have a NumPy array x = np.array([[1, 2, 3], [4, 6, 8]]), and I want to divide every element by y. However, y is not a single number, but an array, y = np.array([2, 4]). I want to divide each row of x by each row of y, to return np.array([[0.5, 1.0, 1.5], [1.0, 1.5, 2.0]).

How can I do this? If I just run x / y, I get an error: ValueError: operands could not be broadcast together with shapes (2,3) (2,)

1
  • 1
    .. x/y[:,None]? Commented Feb 27, 2019 at 16:39

1 Answer 1

1

Operations between multiple arrays must follow numpy's broadcasting rules. Here, your second array has to be reshaped to shape (2, 1) either via

x / y.reshape(2, 1)

or equivalently

x / y[:, np.newaxis]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.