python append two matrix side by side

You are describing the basic usage of np.hstack.

np.hstack((A, B))

There is also an equivalent index trick:

np.c_[A, B]

Also, using np.concatenate with axis=1 will be 4x faster than using numpy.hstack.

In [207]: np.concatenate((A, B), axis=1)
Out[207]: 
array([[ 1,  2,  3, 10, 11],
       [ 4,  5,  6, 12, 13]])

And if you care about performance, np.concatenate is the real war horse.

In [215]: %timeit np.concatenate((A, B), 1)
The slowest run took 12.10 times longer than the fastest.
100000 loops, best of 3: 3.1 µs per loop

In [214]: %timeit np.hstack((A,B))
The slowest run took 6.85 times longer than the fastest.
100000 loops, best of 3: 12.5 µs per loop

In [216]: %timeit np.c_[A, B]
10000 loops, best of 3: 48.7 µs per loop

You can do something like this, basically adding each list in the zipped (A, B) object:

>>> [x + y for x, y in zip(A, B)]
[[1, 2, 3, 10, 11], [4, 5, 6, 12, 13]]

Tags:

Python

Numpy