Python 用 2 个一维数组创建二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17710672/
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 08:59:02  来源:igfitidea点击:

Create 2 dimensional array with 2 one dimensional array

pythonarraysnumpy

提问by Am1rr3zA

I used numpy and scipy and there some function really care about the dimension of the array I have a function name CovexHull(point) which accept the point as 2 dimensional array.

我使用了 numpy 和 scipy 并且有一些函数真正关心数组的维度我有一个函数名称 CovexHull(point) 接受点作为二维数组。

hull = ConvexHull(points)

船体 = ConvexHull(点)

In [1]: points.ndim
Out[1]: 2
In [2]: points.shape
Out[2]: (10, 2)
In [3]: points
Out[3]: 
array([[ 0. ,  0. ],
       [ 1. ,  0.8],
       [ 0.9,  0.8],
       [ 0.9,  0.7],
       [ 0.9,  0.6],
       [ 0.8,  0.5],
       [ 0.8,  0.5],
       [ 0.7,  0.5],
       [ 0.1,  0. ],
       [ 0. ,  0. ]])

As you can see above the points is a numpy with ndim 2.

正如您在上面看到的,这些点是一个带有 ndim 2 的 numpy。

Now I have 2 different numpy array (tp and fp) like this (for example fp)

现在我有 2 个不同的 numpy 数组(tp 和 fp)像这样(例如 fp)

In [4]: fp.ndim
Out[4]: 1
In [5]: fp.shape
Out[5]: (10,)
In [6]: fp
Out[6]: 
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.4,
        0.5, 0.6,  0.9,  1. ])

My question is how can I create a 2 dimensional numpy array effectively like points with tp and fp

我的问题是如何像 tp 和 fp 点一样有效地创建一个二维 numpy 数组

采纳答案by ijmarshall

If you wish to combine two 10 element 1-d arrays into a 2-d array np.vstack((tp, fp)).Twill do it. np.vstack((tp, fp))will return an array of shape (2, 10), and the Tattribute returns the transposed array with shape (10, 2) (i.e. with the two 1-d arrays forming columns rather than rows).

如果你想将两个 10 元素的一维数组组合成一个二维数组np.vstack((tp, fp)).T就可以了。np.vstack((tp, fp))将返回一个形状为 (2, 10) 的数组,并且该T属性返回形状为 (10, 2) 的转置数组(即两个一维数组形成列而不是行)。

>>> tp = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> tp.ndim
1
>>> tp.shape
(10,)

>>> fp = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> fp.ndim
1
>>> fp.shape
(10,)

>>> combined = np.vstack((tp, fp)).T
>>> combined
array([[ 0, 10],
       [ 1, 11],
       [ 2, 12],
       [ 3, 13],
       [ 4, 14],
       [ 5, 15],
       [ 6, 16],
       [ 7, 17],
       [ 8, 18],
       [ 9, 19]])

>>> combined.ndim
2
>>> combined.shape
(10, 2)

回答by Aminu Kano

You can use numpy's column_stack

您可以使用 numpy 的column_stack

np.column_stack((tp, fp))