numpy:将数组按行相乘

问题描述:

我有那些数组:

a = np.array([
     [1,2],
     [3,4],
     [5,6],
     [7,8]])

b = np.array([1,2,3,4])

我希望它们成倍增加:

[[1*1, 2*1],
[3*2, 4*2],
[5*3, 6*3],
[7*4, 8*4]]

...基本上是out[i] = a[i] * b[i],其中a[i].shape(2,),而b[i]然后是标量.

... basically out[i] = a[i] * b[i], where a[i].shape is (2,) and b[i] then is a scalar.

诀窍是什么? np.multiply似乎不起作用:

What's the trick? np.multiply seems not to work:

>>> np.multiply(a, b)
ValueError: operands could not be broadcast together with shapes (4,2) (4)

向b添加轴:

>>> np.multiply(a, b[:, np.newaxis])
array([[ 1,  2],
       [ 6,  8],
       [15, 18],
       [28, 32]])