How to broadcast a row to a column in Python NumPy

2019-06-09 15:49发布

问题:

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.]])