Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate two one-dimensional arrays in NumPy?

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?

like image 631
Daniel Usachev Avatar asked Aug 30 '25 17:08

Daniel Usachev


2 Answers

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
like image 113
kmario23 Avatar answered Sep 02 '25 13:09

kmario23


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
like image 26
titipata Avatar answered Sep 02 '25 15:09

titipata