numpy:将数组按行相乘 [英] numpy: multiply arrays rowwise
本文介绍了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]])
这篇关于numpy:将数组按行相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文