Creating NumPy Vertical Arrays in Python

I use NumPy in Python to work with arrays. This is exactly how I use to create a vertical array:

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

Is there a simpler and more direct way to create vertical arrays?

+7
python arrays numpy
source share
3 answers

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

Alternatively, you can use broadcasting to resize the 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]]) 
+11
source share

You can also use np.newaxis (see examples here )

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

As an additional note

I only realized that you used from numpy import * . Do not do this, as many functions from the Python shared library overlap with numpy (e.g., sum ). When you import * from numpy , you lose the functionality of these functions. Therefore, always use:

 import numpy as np 

which is also easy to enter.

+4
source share

Simplicity and directness 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. Thus, in a sense, extra brackets are pain, but it is rather subjective.

Or, if you want something more like MATLAB, you can use the np.matrix string np.matrix :

 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:

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

Other methods:

 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 
0
source share

All Articles