Python 使用 numpy 数组连接列向量

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

Concatenating column vectors using numpy arrays

pythonvectornumpyconcatenation

提问by green diod

I'd like to concatenate 'column' vectors using numpy arrays but because numpy sees all arrays as row vectors by default, np.hstackand np.concatenatealong any axis don't help (and neither did np.transposeas expected).

我想使用 numpy 数组连接“列”向量,但因为默认情况下 numpy 将所有数组视为行向量,np.hstack并且np.concatenate沿任何轴都无济于事(并且也没有np.transpose按预期进行)。

a = np.array((0, 1))
b = np.array((2, 1))
c = np.array((-1, -1))

np.hstack((a, b, c))
# array([ 0,  1,  2,  1, -1, -1])  ## Noooooo
np.reshape(np.hstack((a, b, c)), (2, 3))
# array([[ 0,  1,  2], [ 1, -1, -1]]) ## Reshaping won't help

One possibility (but too cumbersome) is

一种可能性(但太麻烦)是

np.hstack((a[:, np.newaxis], b[:, np.newaxis], c[:, np.newaxis]))
# array([[ 0,  2, -1], [ 1,  1, -1]]) ##

Are there better ways?

有更好的方法吗?

采纳答案by abudis

I believe numpy.column_stackshould do what you want. Example:

我相信numpy.column_stack应该做你想做的。例子:

>>> a = np.array((0, 1))
>>> b = np.array((2, 1))
>>> c = np.array((-1, -1))
>>> numpy.column_stack((a,b,c))
array([[ 0,  2, -1],
       [ 1,  1, -1]])

It is essentially equal to

它基本上等于

>>> numpy.vstack((a,b,c)).T

though. As it says in the documentation.

尽管。正如文档中所说。

回答by Pavan Yalamanchili

I tried the following. Hope this is good enough for what you are doing ?

我尝试了以下方法。希望这对你正在做的事情足够好?

>>> np.vstack((a,b,c))
array([[ 0,  1],
       [ 2,  1],
       [-1, -1]])
>>> np.vstack((a,b,c)).T
array([[ 0,  2, -1],
       [ 1,  1, -1]])