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 in
Solution 1:
Simple NumPy solution - np.array([...]).T
:
In [6]: np.array([a1, a2]).T
Out[6]:
array([[2000, 20],
[2100, 80],
[2800, 40]])
Another NumPy 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]])
Another "slow" solution 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)]
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
In [151]: %timeit np.column_stack([a1, a2])
100 loops, best of 3: 7.62 ms per loop
In [14]: %timeit np.array([a1, a2]).T
100 loops, best of 3: 6.36 ms per loop # <--- WINNER!
Post a Comment for "How To Convert A 2 1d Arrays To One 1d Arrays But Both Values Should Be Inside One Element"