简单的 NumPy 解决方案 -np.array([...]).T
:
In [6]: np.array([a1, a2]).T
Out[6]:
array([[2000, 20],
[2100, 80],
[2800, 40]])
另一个 NumPy 解决方案,它使用vstack() https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html method:
In [142]: np.vstack((array1, array2)).T
Out[142]:
array([[2000, 20],
[2100, 80],
[2800, 40]])
或使用np.column_stack() https://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html:
In [144]: np.column_stack([array1, array2])
Out[144]:
array([[2000, 20],
[2100, 80],
[2800, 40]])
另一个“慢”的解决方案是使用内置的zip() https://docs.python.org/3/library/functions.html#zip功能?
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)]
Timing对于两个 1M 元素数组:
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!