user2991243 user2991243 - 2 months ago 24
Python Question

Create vertical numpy arrays in python

I'm using

NumPy
in
Python
to work with arrays. This is the way I'm using to create a vertical array:

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


Is any more simple and direct way to create vertical arrays?

Answer

You can use reshape or vstack :

>>> a=np.arange(1,4)
>>> a
array([1, 2, 3])
>>> a.reshape(3,1)
array([[1],
       [2],
       [3]])
>>> np.vstack(a)
array([[1],
       [2],
       [3]])

Also, you can use broadcasting in order to reshape your array:

In [32]: a = np.arange(10)
In [33]: a
Out[33]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [34]: a[:,None]
Out[34]: 
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])