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?
Use numpy. concatenate : >>> import numpy as np >>> np. concatenate((A, B)) matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]])
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.
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.
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 are describing the basic usage of np.hstack
.
np.hstack((A, B))
There is also an equivalent index trick:
np.c_[A, B]
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]]
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]]
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