用向量数组乘以标量的numpy数组

9 投票
1 回答
6730 浏览
提问于 2025-04-16 16:28

我有一个包含向量的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]])

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答