使用numpy数组串联列向量 [英] Concatenating column vectors using numpy arrays

查看:234
本文介绍了使用numpy数组串联列向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用numpy数组连接列"向量,但是因为numpy默认情况下将所有数组视为行向量,所以沿任何轴的np.hstacknp.concatenate都无济于事(np.transpose也没有预期的).

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

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]]) ##

还有更好的方法吗?

推荐答案

我相信 numpy.column_stack 应该可以执行您想要的操作. 示例:

I believe numpy.column_stack should do what you want. Example:

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

它基本上等于

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

虽然.如文档中所述.

though. As it says in the documentation.

这篇关于使用numpy数组串联列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆