Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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!

like image 768
Roohollah Etemadi Avatar asked Sep 01 '20 07:09

Roohollah Etemadi


2 Answers

output = np.zeros((2,4), int)
output[:, :2] = a    # broadcasts (2,) to (1,2) to (2,2)
output[:, 2:] = b
like image 119
hpaulj Avatar answered Oct 03 '22 03:10

hpaulj


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]])
like image 36
yatu Avatar answered Oct 03 '22 04:10

yatu