Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list comprehension with numpy arrays - bad practice?

Tags:

python

numpy

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!

like image 773
laszlopanaflex Avatar asked Nov 05 '15 18:11

laszlopanaflex


1 Answers

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
like image 158
Divakar Avatar answered Nov 06 '22 23:11

Divakar