使用numpy数组连接列向量

gre*_*iod 21 python numpy vector concatenation

我想使用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
Run Code Online (Sandbox Code Playgroud)

一种可能性(但过于繁琐)是

np.hstack((a[:, np.newaxis], b[:, np.newaxis], c[:, np.newaxis]))
# array([[ 0,  2, -1], [ 1,  1, -1]]) ##
Run Code Online (Sandbox Code Playgroud)

还有更好的方法吗?

abu*_*dis 48

我相信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]])
Run Code Online (Sandbox Code Playgroud)

它基本上等于

>>> numpy.vstack((a,b,c)).T
Run Code Online (Sandbox Code Playgroud)

虽然.正如文档中所述.