numpy的:串联多层面的一维数组 [英] Numpy: Concatenating multidimensional and unidimensional arrays

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

问题描述

我有一个2x2的阵列numpy的:

I have a 2x2 numpy array :

x = array(([[1,2],[4,5]]))

这是我必须合并(或堆栈,如果你愿意的话)与一维数组:

which I must merge (or stack, if you wish) with a one-dimensional array :

y = array(([3,6]))

将其添加到排尾,从而使2×3 numpy的数组,它会像这样的输出:

by adding it to the end of the rows, thus making a 2x3 numpy array that would output like so :

阵列([[1,2,3]
       [4,5,6]])

array([[1, 2, 3], [4, 5, 6]])

现在这个在numpy的指南建议的方法是:

now the proposed method for this in the numpy guides is :

hstack((x,y))

不过这并不工作,返回了以下错误:

however this doesn't work, returning the following error :

ValueError错误:数组必须具有相同的维数

ValueError: arrays must have same number of dimensions

可能唯一的解决办法似乎是要做到这一点:

The only workaround possible seems to be to do this :

hstack((x, array(([y])).T ))

这工作,但看起来和听起来相当的hackish。似乎没有其他的方式来转给定的数组,所以hstack能够消化它。我想知道,是否有一个更清洁的方式做到这一点?岂不会有一种方式,numpy的猜测我想做的事?

which works, but looks and sounds rather hackish. It seems there is not other way to transpose the given array, so that hstack is able to digest it. I was wondering, is there a cleaner way to do this? Wouldn't there be a way for numpy to guess what I wanted to do?

推荐答案

unutbu的回答工作在一般情况下,但在这种情况下,也有np.column_stack

unutbu's answer works in general, but in this case there is also np.column_stack

>>> x
array([[1, 2],
       [4, 5]])
>>> y
array([3, 6])

>>> np.column_stack((x,y))
array([[1, 2, 3],
       [4, 5, 6]])

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

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