Multiply Numpy n x 2 array by n x 1 array

Question:

Assuming I have a Numpy n x 2 array y: array([[1, 1], [2, 3], [1, 4], ...]) and a Numpy n x 1 array x: array([2, 4, 5, ...]), how can I efficiently obtain the following result, n x 2 array: array([2, 2], [8, 12], [5, 20], ...]), where each element (array) of the y is multiplied by corresponding value from array x?

I can do it via a cycle but looking for more performant approaches.

Asked By: Mikhail

||

Answers:

With an actual n-by-1 x, you could just do x * y. Your x is 1-dimensional, n-not-by-anything, so you’d have to reshape it first:

x.reshape((n, 1)) * y
Answered By: user2357112