如何将2个1d数组转换为一个1d数组,但两个值都应在一个元素内 [英] How to convert a 2 1d arrays to one 1d arrays but both values should be inside one element
本文介绍了如何将2个1d数组转换为一个1d数组,但两个值都应在一个元素内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的不怎么恰当地表达这句话,所以我事先表示歉意. 所以可以说我有2个1D数组
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]
现在如何将它们转换为python中的2d数组,如下所示
Now how do i convert them into an 2d array in python like shown below
2dArray = [[2000, 20], [2100, 80], [2800, 40]]
所以2个id数组看起来像上面的python中的那个.
So 2 id arrays to look like the one above in python.
推荐答案
简单的NumPy解决方案-np.array([...]).T
:
Simple NumPy solution - np.array([...]).T
:
In [6]: np.array([a1, a2]).T
Out[6]:
array([[2000, 20],
[2100, 80],
[2800, 40]])
另一种NumPy解决方案,它使用 vstack()方法:
Another NumPy solution, which uses vstack() method:
In [142]: np.vstack((array1, array2)).T
Out[142]:
array([[2000, 20],
[2100, 80],
[2800, 40]])
或使用 np.column_stack() :
In [144]: np.column_stack([array1, array2])
Out[144]:
array([[2000, 20],
[2100, 80],
[2800, 40]])
另一种慢"的解决方案是使用内置的 zip() 功能?
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]])
说明:
In [132]: list(zip(array1, array2))
Out[132]: [(2000, 20), (2100, 80), (2800, 40)]
定时:两个1M元素数组:
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!
这篇关于如何将2个1d数组转换为一个1d数组,但两个值都应在一个元素内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文