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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44409084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:59:18  来源:igfitidea点击:

How to zip two 1d numpy array to 2d numpy array

pythonnumpy

提问by zjffdu

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

我有两个 numpy 一维数组,例如:

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

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

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

采纳答案by ébe Isaac

The answer lies in your question:

答案就在你的问题中:

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



Edit:

编辑:

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).

尽管我的帖子按照 OP 的要求给出了答案,但转换到列表并返回到 NumPy 数组需要一些开销(对于大型数组很明显)。

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

因此,dstack这将是一种计算效率高的替代方案(参考@zipa 的回答)。我dstack在发布此答案时并不知道,因此感谢 @zipa 将其介绍到这篇文章中。

回答by zipa

If you have numpy arrays you can use dstack():

如果你有 numpy 数组,你可以使用dstack()

import numpy as np

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

c = np.dstack((a,b))
#or
d = np.column_stack((a,b))

>>> c
array([[[ 1,  6],
        [ 2,  7],
        [ 3,  8],
        [ 4,  9],
        [ 5, 10]]])
>>> d
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])

>>> c.shape
(1, 5, 2)
>>> d.shape
(5, 2)

回答by akash karothiya

You can use zip

您可以使用 zip

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