How to concatenate a vector into rows of a numpy matrix?

Viewed 459

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!

4 Answers
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]])

Well, I did a “quick” comparison of your solution with others. As all of them are able to achieve the same result, it is important to see which one performs better.

enter image description here

You can use reshape and concatenate:

np.concatenate((np.concatenate((a.reshape(1,2), a.reshape(1,2))), b), axis=1)

Or maybe better using tile:

np.concatenate((np.tile(a.reshape(1,2), (2,1)), b), axis=1)
Related