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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With