使用numpy数组进行列表理解-不好的做法? [英] list comprehension with numpy arrays - bad practice?

查看:69
本文介绍了使用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.

这是有问题的代码:

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)])

此处的目标是获得与'a'形状相同的数组,其中'a'的第一个元素的值乘以'b'的第一个元素和'a'的第二个元素的值'乘以'b'的第二个元素

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 的方法是使用

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]

一旦尺寸被扩展,您也可以使用np.multiply来获得相同的效果,就像这样-

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

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

最重要的是,这里有一些性能数据可以说服您使用broadcasting-

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

这篇关于使用numpy数组进行列表理解-不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆