1

I couldn't seem to find this problem on stackoverflow although I'm sure someone has asked this before.

I have two numpy arrays as follows:

a = np.ones(shape = (2,10))
b = np.ones(2)

I want to multiply the first row of 10 of a by the first number in b and the second row by the second number. I can do this using lists as follows:

np.array([x*y for x,y in zip(b,a)])

I was wondering if there is a way to do this in numpy that would be a similar one liner to the list method.

I am aware I can reshape a to (1,2,10) and b to (2,1) to effectively achieve this - is this the only solution? Or is there a numpy method that can do this without manually reshaping.

1
  • Broadcasting adds leading dimensions as needed, but in this case you need a new trailing one. Commented Jun 3, 2020 at 2:18

1 Answer 1

1

This might be what you are looking for:

a*np.tile(np.expand_dims(b,axis=1),(1,10))

If you want to make use of the automatic numpy broadcasting, you need to reshape b first:

np.multiply(a, b.reshape(2,1))
Sign up to request clarification or add additional context in comments.

3 Comments

That is! I'm guessing from this answer, there probably isn't a single built-in numpy method for this specific array multiplication scenario?
I edited my answer, might be clearer this time. You can use the multiply function for automating your broadcasting, but you still need to reshape to guide the function for the tiling dimension.
a * b[:, None] is another way to write the broadcasting solution.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.