Numpy: Concatenating multidimensional and unidimensional arrays

泪湿孤枕 提交于 2019-12-18 12:16:47

问题


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 array 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?


回答1:


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



回答2:


Also works:

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


来源:https://stackoverflow.com/questions/4158388/numpy-concatenating-multidimensional-and-unidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!