将NumPy标量数组乘以向量数组

9
我有一个numpy向量数组,需要乘以一个标量数组。例如:
>>> import numpy
>>> x = numpy.array([0.1, 0.2])
>>> y = numpy.array([[1.1,2.2,3.3],[4.4,5.5,6.6]])

我可以这样单独地对元素进行乘法操作:

>>> x[0]*y[0]
array([ 0.11,  0.22,  0.33])

但是当我尝试将整个数组相乘时,会出现以下情况:
>>> x*y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape

我认为这与广播规则有关。使用numpy,逐元素地将这两个数组相乘的最快方法是什么?
1个回答

20
I[1]: x = np.array([0.1, 0.2])

I[2]: y = np.array([[1.1,2.2,3.3],[4.4,5.5,6.6]])


I[3]: y*x[:,np.newaxis]
O[3]: 
array([[ 0.11,  0.22,  0.33],
       [ 0.88,  1.1 ,  1.32]])

如果你和我一样好奇为什么这个能够工作,可以阅读 https://dev59.com/7l4b5IYBdhLWcg3wYAf6。 - John Henckel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接