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?
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]])
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.
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]])
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
shift+enter
for editing :D