如何将两个1d numpy数组压缩为2d numpy数组 [英] How to zip two 1d numpy array to 2d numpy array
问题描述
我有两个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.
这篇关于如何将两个1d numpy数组压缩为2d numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!