Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

python - numpy: multiply arrays rowwise

I have those arrays:

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

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

and I want them to multiply like so:

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

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

add an axis to b:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...