Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a numpy vertical arange?

>>> print np.array([np.arange(10)]).transpose()

[[0]
 [1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]
 [9]]

Is there a way to get a vertical arange without having to go through these extra steps?

like image 487
Jason S Avatar asked Aug 10 '13 15:08

Jason S


2 Answers

You can use np.newaxis:

>>> np.arange(10)[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

np.newaxis is just an alias for None, and was added by numpy developers mainly for readability. Therefore np.arange(10)[:, None] would produce the same exact result as the above solution.

Edit:

Another option is:

np.expand_dims(np.arange(10), axis=1)

numpy.expand_dims

like image 175
Akavall Avatar answered Oct 11 '22 08:10

Akavall


I would do:

np.arange(10).reshape((10, 1))

Unlike np.array, reshape is a light weight operation which does not copy the data in the array.

like image 34
Bi Rico Avatar answered Oct 11 '22 08:10

Bi Rico