连接两个一维到两列的数组

时间:2013-01-23 15:02:28

标签: python arrays numpy

a = np.array([1, 2, 3])
aa = np.array([1], [2], [3])
b = np.array([1, 2, 3])
bb = np.array([1], [2], [3])
np.concatenate((a, b), axis = 1)
array([1, 2, 3, 1, 2, 3])     # It's ok, that's what I was expecting
np.concatenate((a, b), axis = 0)
array([1, 2, 3, 1, 2, 3])     # It's not ok, that's not what I was expecting

我在期待:

array([[1, 2, 3],
       [1, 2, 3]])

即使使用aa和bb,我也会得到同样的不一致。 那么是否有一个简单的解决方案可以沿轴0连接两个一维数组?

1 个答案:

答案 0 :(得分:5)

请注意,ab都是一维的;没有轴1连接起来。你想要vstack

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = a.copy()
>>> np.vstack([a,b])
array([[1, 2, 3],
       [1, 2, 3]])

或者,您可以先重塑ab

>>> np.concatenate([a[np.newaxis,:],b[np.newaxis,:]],axis = 0)
array([[1, 2, 3],
       [1, 2, 3]])