如何将两个1d numpy数组压缩为2d numpy数组

问题描述:

我有两个numpy 1d数组,例如:

I have two numpy 1d arrays, e.g:

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

那我怎样才能得到一个2d数组[[1,6], [2,7], [3,8], [4,9], [5, 10]]?

Then how can I get one 2d array [[1,6], [2,7], [3,8], [4,9], [5, 10]]?

答案在于您的问题:

np.array(list(zip(a,b)))


尽管我的帖子按照OP的要求给出了答案,但转换为list并返回NumPy数组会花费一些开销(对于大型数组而言很明显).

Although my post gives the answer as requested by the OP, the conversion to list and back to NumPy array takes some overhead (noticeable for large arrays).

因此,dstack将是计算有效的替代方法(请参阅@zipa的答案).发布此答案时,我还没有意识到dstack,因此将@zipa引入本帖子的功劳归功于@zipa.

Hence, dstack would be a computationally efficient alternative (ref. @zipa's answer). I was unaware of dstack at the time of posting this answer so credits to @zipa for introducing it to this post.