kv manohar kv manohar - 2 months ago 19
Python Question

Stacking arrays in numpy using vstack

array1.shape
gives (180, )
array2.shape
gives (180, 1)

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?

Answer

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