Suppose numpy vector a and matrix b as below:
import numpy as np
a = np.array([1,2])
b = np.array([[3,4],[5,6]])
I want to concatenate vector a into each row of matrix b. The expected output is as below:
output=np.array([[1,2,3,4],[1,2,5,6]])
I have a working code as below:
output=np.array([np.concatenate((a,row)) for row in b] )
Is there any faster numpy function to perform such a task? Any suggestion is appreciated!
output = np.zeros((2,4), int)
output[:, :2] = a # broadcasts (2,) to (1,2) to (2,2)
output[:, 2:] = b
You can broadcast a
to the shape of b
with np.broadcast_to
and then stack them horizontally with np.hstack
:
np.hstack([np.broadcast_to(a, b.shape), b])
array([[1, 2, 3, 4],
[1, 2, 5, 6]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With