7

I am wondering if the below approach would be considered bad practice, and if so, if someone could give some guidance towards another approach.

Here is the code in question:

a = np.array([[1,2,3],[4,5,6]])
b = np.array([-5,5])
c = np.array([np.multiply(a[x],b[x]) for x in range(2)])

The objective here is to obtain an array of the same shape as 'a' where the values in the first element of 'a' are multiplied by the first element of 'b' and the values in the second element of 'a' are multiplied by the second element of 'b'

The above code works, but given the mixture of lists/arrays involved I'm concerned this is advised against - but I'm not clear on a more elegant solution. Many thanks in advance!

1 Answer 1

12

NumPythonic way would be to extend the dimensions of b to a 2D array with np.newaxis/None and then let broadcasting come into play for a vectorized elementwise multiplication. The implementation would look like this -

c = a * b[:,None]

Once the dimensions are extended, you can also use np.multiply for the same effect, like so -

c = np.multiply(a,b[:,None])

Most importantly, here's some performance numbers to persuade you on using broadcasting -

In [176]: a = np.random.rand(2000,3000)

In [177]: b = np.random.rand(2000)

In [178]: %timeit np.array([np.multiply(a[x],b[x]) for x in range(a.shape[0])])
10 loops, best of 3: 118 ms per loop

In [179]: %timeit a * b[:,None]
10 loops, best of 3: 63.8 ms per loop

In [180]: %timeit np.multiply(a,b[:,None])
10 loops, best of 3: 64 ms per loop
Sign up to request clarification or add additional context in comments.

2 Comments

That's very helpful, thanks! I'll have to understand the "newaxis" concept better. b[:None].shape would still indicate a 1d array and not 2, so i wouldn't necessarily expect this to have worked...
b[:None] is very different from b[:, None]. The comma is significant. The first is part of a slice, slice(None,None,None). The second is understood by numpy to have this special newaxis meaning.

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.