简体   繁体   English

使用numpy数组进行列表理解-错误的做法?

[英]list comprehension with numpy arrays - bad practice?

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' 此处的目的是获得与'a'形状相同的数组,其中'a'的第一个元素的值乘以'b'的第一个元素,而第二个元素'a'的值相乘通过“ 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 . NumPythonic的方法是使用np.newaxis/Noneb的维度扩展为2D数组,然后让broadcasting开始进行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 - 扩展尺寸后,您也可以使用np.multiply达到相同的效果,如下所示-

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

Most importantly, here's some performance numbers to persuade you on using broadcasting - 最重要的是,以下一些性能数据可以说服您使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM