7
>>> 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?

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • You're already doing some unnecessary steps there - the `np.array()` and the `[]` are unnecessary since `np.arange` returns a numpy array. You can just do `np.arange(10).transpose()` – Brionius Aug 10 '13 at 16:04
  • 4
    @Brionius, `transpose` of a 1d array doesn't do anything. The OP is using the `[]` to add an extra dimension to the array and is asking if there is a more efficient way to achieve the same result. – Bi Rico Aug 10 '13 at 16:09
  • @BiRico Ah, you're right, my mistake. – Brionius Aug 10 '13 at 16:15
  • 2
    "You're already doing some unnecessary steps there" -- I figured, that's why I asked. – Jason S Aug 10 '13 at 16:18
  • @BiRico is there a different way to add a dimension to the array? For some reason my `np.array` is not actually working...idk why. – Charlie Parker Jul 06 '17 at 17:05

2 Answers2

16

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

Akavall
  • 82,592
  • 51
  • 207
  • 251
  • @JasonS, I added a link with an example. – Akavall Aug 10 '13 at 16:24
  • @JasonS - Have a look at: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#arrays-indexing The docs are rather consice, so see one of the guides or books (as Akavall linked to) for more examples. – Joe Kington Aug 10 '13 at 16:25
  • @JasonS I don't know either... I [just posted a question](http://stackoverflow.com/q/18163958/832621) for that... – Saullo G. P. Castro Aug 10 '13 at 16:27
  • 1
    @SaulloCastro, good question, so I guess `np.newaxis` was introduced just because it is easier to read. – Akavall Aug 10 '13 at 16:36
14

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.

Bi Rico
  • 25,283
  • 3
  • 52
  • 75
  • 13
    On a side note, you can also do `whatever.reshape(-1, 1)`, to avoid having to specify the size of the first dimension. – Joe Kington Aug 10 '13 at 16:20