1

I am creating a numpy array using the following:

X = np.linspace(-5, 5, num=500)

This generates points evenly sampled 500 points between -5 and 5. The shape of the resulting array is: (500,). Now, I need to pass it to a function that expects a 2-D array. So, I can reshape it as:

X = X.reshape((500, 1))

However, I noticed that X = X[:, None] has the same effect. For the life of me though, I cannot understand what this syntax is doing. Hoping someone can shed some light on this.

1
  • 2
    None is np.newaxis - this page on advanced indexing explains its use in a bit of detail and might be a useful reference. Commented Aug 26, 2015 at 14:30

2 Answers 2

7

The syntax X[: ,None] is actually the same as:

X[:, np.newaxis]

which is adding a new dimension to your original array.

Sign up to request clarification or add additional context in comments.

Comments

3

The Python interpreter translates

 x[:,None]

to

 x.__getitem__((slice(None,None,None), None))

and the ndarray implementation of __getitem__ acts in much the same way as x.reshape(500,1). Implementation details will differ, but the effect is the same. `

So at a syntax level, it's just normal Python. But the numpy semantics give it a distinctive meaning.

 x[:, np.newaxis] 

may be clearer, but np.newaxis is just an alias for None:

In [48]: np.newaxis is None
Out[48]: True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.