0

I'm following certain tutorials for science proposals in Python and I've encounter this way of using indexing:

import numpy as np
l=np.array([8,5,2,3])
print(l[:,None])

What this print returns is:

[[8]
 [5]
 [2]
 [3]]

It is obvious what this code does and I find it very useful for my proposal but It would never have occurred to me using it because I don't understand what this slicing syntax is saying.

Anyone can explain me how this type of slicing works?

Thanks in advance.

Carlos
  • 889
  • 3
  • 12
  • 34
  • 1
    ':' is a place holder for [all of them](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) – Stephen Rauch Jan 15 '18 at 17:05
  • I understand this, but what I don't really understand is passing the second part ',None', because the original array has not two dimensions. – Carlos Jan 15 '18 at 17:07

2 Answers2

0

: is placeholder for all elements and None is np.newaxis, if you are trying to slice extra shape then None will tell numpy make new dimension.

So the proper way to write your example and avoid confusion will be:

import numpy as np
l = np.array([8, 5, 2, 3])
print(l[:, np.newaxis])
aiven
  • 3,775
  • 3
  • 27
  • 52
0

No, this is upscaling of the array dimension from 1D to 2D, a column vector to be precise. The most common way to do this is using None or np.newaxis :

In [317]: l = np.array([8,5,2,3])

In [318]: l[:, np.newaxis]
Out[318]: 
array([[8],
       [5],
       [2],
       [3]])

In [319]: l.shape
Out[319]: (4,)

In [320]: l[:, np.newaxis].shape
Out[320]: (4, 1)

But, you can also convert it into a row vector using:

In [321]: l[np.newaxis, :]
Out[321]: array([[8, 5, 2, 3]])

In [322]: (l[np.newaxis, :]).shape
Out[322]: (1, 4)

So, : means select all the elements from the array along a particular axis during the slicing operation.

See how np.newaxis work for more information.

kmario23
  • 57,311
  • 13
  • 161
  • 150