Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python append two matrix side by side [duplicate]

Tags:

python

numpy

I am having some problem with python.

    A= [ [1,2,3]
         [4,5,6]
       ]

   B = [ [10,11]
         [12,13]
       ]

I want to have:

   C = [A B]
     = [ [1,2,3,  10, 11]
         [4,5,6,  12, 13]
       ]

How do I do that in python?

like image 911
wrek Avatar asked Apr 10 '17 22:04

wrek


People also ask

How do you append 2 matrices in Python?

Use numpy. concatenate : >>> import numpy as np >>> np. concatenate((A, B)) matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]])

Can you add two arrays in Python?

In Python, it's easy to add one array to another with the built-in Python library NumPy. NumPy is a free Python library equipped with a collection of complex mathematical operations suitable for processing statistical data.

How do you print two arrays in Python?

Use the numpy. column_stack((A, B)) method with a tuple. The tuple must be represented with () parenthesizes representing a single argument with as many matrices/arrays as you want. Numpy column_stack is useful for AI/ML applications when comparing the predicted results with the expected answers.


4 Answers

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
like image 141
kmario23 Avatar answered Nov 15 '22 21:11

kmario23


You are describing the basic usage of np.hstack.

np.hstack((A, B))

There is also an equivalent index trick:

np.c_[A, B]
like image 31
wim Avatar answered Nov 15 '22 20:11

wim


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]]
like image 32
blacksite Avatar answered Nov 15 '22 20:11

blacksite


can't tell if you're asking about numpy arrays (per your tag) or lists of lists (matrix per your title)... but:

to concatenate lists you just add them together:

A = [[1,2,3],[4,5,6]]
B = [[10,11],[12,13]]
C = [A[0]+B[0],A[1]+B[1]]

print C

>>>
[[1, 2, 3, 10, 11], [4, 5, 6, 12, 13]]

if you have arrays to begin with you can use the append method:

import numpy as np
A = np.array([[1,2,3],[4,5,6]])
B = np.array([[10,11],[12,13]])
C = np.array([np.append(A[0],B[0]),np.append(A[1],B[1])])

print C

>>>
[[ 1  2  3 10 11]
 [ 4  5  6 12 13]]
like image 28
litepresence Avatar answered Nov 15 '22 19:11

litepresence