[英]Stacking arrays in numpy using vstack
array1.shape
gives (180, ) array2.shape
gives (180, 1) array1.shape
给出(180,) array2.shape
给出( array2.shape
)
What's the difference between these two? 这两者有什么区别? And because of this difference I'm unable to stack them using 由于这种差异,我无法使用它们进行堆叠
np.vstack((array2, array1))
What changes should I make to array1 shape so that I can stack them up? 我应该对array1的形状进行哪些更改,以便我可以将它们叠加起来?
Let's define some arrays: 让我们定义一些数组:
>>> x = np.zeros((4, 1))
>>> y = np.zeros((4))
As is, these arrays fail to stack: 这样,这些数组无法堆叠:
>>> np.vstack((x, y))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/numpy/core/shape_base.py", line 230, in vstack
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
However, with a simple change, they will stack: 但是,通过简单的更改,它们将堆叠:
>>> np.vstack((x, y[:, None]))
array([[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.]])
Alternatively: 或者:
>>> np.vstack((x[:, 0], y))
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
In [81]: x1=np.ones((10,)); x2=np.ones((10,1))
One array is 1d, the other 2d. 一个数组是1d,另一个是2d。 vertical
stack requires 2 dimensions, vertical and horizontal. vertical
堆栈需要2个尺寸,垂直和水平。 So np.vstack
passes each input through np.atleast_2d
: 所以np.vstack
穿过每个输入np.atleast_2d
:
In [82]: np.atleast_2d(x1).shape
Out[82]: (1, 10)
But now we have a (1,10) array and a (10,1) - they can't be joined in either axis. 但现在我们有一个(1,10)数组和一个(10,1) - 它们不能在任何一个轴上连接。
But if we reshape x1
so it is (10,1)
, then we can join it with x2
in either direction: 但是如果我们重塑x1
所以它是(10,1)
,那么我们可以在任一方向上与x2
连接:
In [83]: np.concatenate((x1[:,None],x2), axis=0).shape
Out[83]: (20, 1)
In [84]: np.concatenate((x1[:,None],x2), axis=1).shape
Out[84]: (10, 2)
Print out the two arrays: 打印出两个数组:
In [86]: x1
Out[86]: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
In [87]: x2
Out[87]:
array([[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.]])
How can you concatenate those two shapes without some sort of adjustment? 如何在没有某种调整的情况下连接这两种形状?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.