开发者

Numpy: Concatenating multidimensional and unidimensional arrays

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

by adding it to the end of the rows, thus making a 2x3 numpy ar开发者_如何学Goray that would output like so :

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

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

hstack((x,y))

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

ValueError: arrays must have same number of dimensions

The only workaround possible seems to be to do this :

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

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


Also works:

In [22]: np.append(x, y[:, np.newaxis], axis=1)
Out[22]: 
array([[1, 2, 3],
       [4, 5, 6]])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜