I have two arrays A = [a1, ..., an]
and B = [b1, ..., bn]
.
I want to get new matrix C that is equal to
[[a1, b1],
[a2, b2],
...
[an, bn]]
How can I do it using numpy.concatenate
?
How about this very simple but fastest solution ?
In [73]: a = np.array([0, 1, 2, 3, 4, 5])
In [74]: b = np.array([1, 2, 3, 4, 5, 6])
In [75]: ab = np.array([a, b])
In [76]: c = ab.T
In [77]: c
Out[77]:
array([[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6]])
But, as Divakar pointed out, using np.column_stack
gives the answer directly like:
In [85]: np.column_stack([a, b])
Out[85]:
array([[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6]])
Efficiency (in descending order)
Interestingly, my simple solution turns out to be the fastest. (little faster than np.concatenate
, twice as fast as np.column_stack
and thrice as fast as np.vstack
)
In [86]: %timeit np.array([a, b]).T
100000 loops, best of 3: 4.44 µs per loop
In [87]: %timeit np.concatenate((a[:,None], b[:,None]), axis=1)
100000 loops, best of 3: 5.6 µs per loop
In [88]: %timeit np.column_stack([a, b])
100000 loops, best of 3: 9.5 µs per loop
In [89]: %timeit np.vstack((a, b)).T
100000 loops, best of 3: 14.7 µs per loop
You can also use np.vstack
then transpose the matrix after
import numpy as np
A = [1, 2, 3]
B = [4, 5, 6]
C = np.vstack((A, B)).T
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