22

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?

3

4 Answers 4

29

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]])
2
  • It would be better if you could add links to your function Apr 15, 2015 at 19:03
  • 1
    @BhargavRao i was doing that ;)
    – Mazdak
    Apr 15, 2015 at 19:04
4

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.

4

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.