2012-10-14 173 views
1

如果我有两个ndarrays:vstack numpy的阵列

a.shape # returns (200,300, 3) 
b.shape # returns (200, 300) 

numpy.vstack((a,b)) # Gives error 

将打印出来的错误: ValueError异常:数组必须具有相同的维数

我试图做vstack((a.reshape(-1,300), b)哪种作品,但输出非常奇怪。

回答

0

您不指定您实际需要的最终形状。如果是(200,300,4),你可以使用dstack代替:

>>> import numpy as np 
>>> a = np.random.random((200,300,3)) 
>>> b = np.random.random((200,300)) 
>>> c = np.dstack((a,b)) 
>>> c.shape 
(200, 300, 4) 

基本上,当你堆叠,长度在所有其它轴一致。

[更新基于评论:]

如果你想(800,300),你可以尝试这样的事:

>>> a = np.ones((2, 3, 3)) * np.array([1,2,3]) 
>>> b = np.ones((2, 3)) * 4 
>>> c = np.dstack((a,b)) 
>>> c 
array([[[ 1., 2., 3., 4.], 
     [ 1., 2., 3., 4.], 
     [ 1., 2., 3., 4.]], 

     [[ 1., 2., 3., 4.], 
     [ 1., 2., 3., 4.], 
     [ 1., 2., 3., 4.]]]) 
>>> c.T.reshape(c.shape[0]*c.shape[-1], -1) 
array([[ 1., 1., 1.], 
     [ 1., 1., 1.], 
     [ 2., 2., 2.], 
     [ 2., 2., 2.], 
     [ 3., 3., 3.], 
     [ 3., 3., 3.], 
     [ 4., 4., 4.], 
     [ 4., 4., 4.]]) 
>>> c.T.reshape(c.shape[0]*c.shape[-1], -1).shape 
(8, 3) 
+0

我想并排堆放的图像侧。有没有办法在a和b的第一轴上堆叠? – user1695915