'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 there a simple and more direct way to create vertical arrays?



Solution 1:[1]

You can also use np.newaxis (See Examples here)

>>> import numpy as np
>>> np.arange(3)[:, np.newaxis]
array([[0],
       [1],
       [2]])

As a side note

I just realized that you have used, from numpy import *. Do not do so as many functions from the Python generic library overlap with numpy (for e.g. sum). When you import * from numpy you lose the functionality of those functions. Hence always use :

import numpy as np

which is also easy to type.

Solution 2:[2]

The best way in my experience is to use reshape(-1, 1) because you don't have to specify the size of the array. It works like this:

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

Solution 3:[3]

Simplicity and directness is in the eye of the beholder.

In [35]: a = np.array([[1],[2],[3]])
In [36]: a.flags
Out[36]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
In [37]: b=np.array([1,2,3]).reshape(3,1)
In [38]: b.flags
Out[38]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

The first is shorter and owns its data. So in a sense the extra brackets are a pain, but it's a rather subjective one.

Or if you want something more like MATLAB you could use the np.matrix string format:

c=np.array(np.matrix('1;2;3'))
c=np.mat('1;2;3').A

But I usually don't worry about the OWNDATA flag. One of my favorite sample arrays is:

np.arange(12).reshape(3,4)

Other ways:

np.atleast_2d([1,2,3]).T
np.array([1,2,3],ndmin=2).T
a=np.empty((3,1),int);a[:,0]=[1,2,3] # OWNDATA

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 elbashmubarmeg
Solution 3 Peter Mortensen