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

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

问题描述

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

a = np.array((0, 1))b = np.array((2, 1))c = np.array((-1, -1))np.hstack((a, b, c))# 数组([ 0, 1, 2, 1, -1, -1]) ## Noooooonp.reshape(np.hstack((a, b, c)), (2, 3))# array([[ 0, 1, 2], [ 1, -1, -1]]) ## 整形无济于事

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

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

有更好的方法吗?

解决方案

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

<预><代码>>>>a = np.array((0, 1))>>>b = np.array((2, 1))>>>c = np.array((-1, -1))>>>numpy.column_stack((a,b,c))数组([[ 0, 2, -1],[ 1, 1, -1]])

本质上等于

<预><代码>>>>numpy.vstack((a,b,c)).T

虽然.正如文档中所说.

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

Are there better ways?

解决方案

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

It is essentially equal to

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

though. As it says in the documentation.

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

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