How to broadcast a row to a column in Python NumPy?

一个人想着一个人 提交于 2019-12-08 10:50:30

问题


I have a row vector R and a column vector C. I want to add them to create an array A with height equal to size of R and width equal to size of C as follows: A[i,j] = R[i] + C[j]

What's the most efficient way of doing this?


回答1:


R + C[:, numpy.newaxis]

Does the trick for me.

For example

import numpy as np
r = np.ones(5)
c = np.ones(4) * 2
r + c[:, np.newaxis]

gives

array([[ 3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.]])


来源:https://stackoverflow.com/questions/47915142/how-to-broadcast-a-row-to-a-column-in-python-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!