Samuel Varghese - 22 days ago 6
Python Question

# How to convert a 2 1d arrays to one 1d arrays but both values should be inside one element

i really dont how to phrase this properly so I apologise in advance.
So lets say i have 2, 1D arrays

``````array1 = [2000, 2100, 2800]
array2 =[20, 80, 40]
``````

Now how do i convert them into an 2d array in python like shown below

``````2dArray = [[2000, 20], [2100, 80], [2800, 40]]
``````

So 2 id arrays to look like the one above in python.

One of solutions would be to use built-in zip() function?

``````In [131]: np.array(list(zip(array1, array2)))
Out[131]:
array([[2000,   20],
[2100,   80],
[2800,   40]])
``````

Explanation:

``````In [132]: list(zip(array1, array2))
Out[132]: [(2000, 20), (2100, 80), (2800, 40)]
``````

Or a NumPy vectorized solution, which uses vstack() method:

``````In [142]: np.vstack((array1, array2)).T
Out[142]:
array([[2000,   20],
[2100,   80],
[2800,   40]])
``````

or using np.column_stack():

``````In [144]: np.column_stack([array1, array2])
Out[144]:
array([[2000,   20],
[2100,   80],
[2800,   40]])
``````

Timing for two 1M elements arrays:

``````In [145]: a1 = np.random.randint(0, 10**6, 10**6)

In [146]: a2 = np.random.randint(0, 10**6, 10**6)

In [147]: a1.shape
Out[147]: (1000000,)

In [148]: a2.shape
Out[148]: (1000000,)

In [149]: %timeit np.array(list(zip(a1, a2)))
1 loop, best of 3: 1.78 s per loop

In [150]: %timeit np.vstack((a1, a2)).T
100 loops, best of 3: 6.4 ms per loop    # <--- WINNER!

In [151]: %timeit np.column_stack([a1, a2])
100 loops, best of 3: 7.62 ms per loop
``````