Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy array slice using None

This had me scratching my head for a while. I was unintentionally slicing an array with None and getting something other than an error (I expected an error). Instead, it returns an array with an extra dimension.

>>> import numpy >>> a = numpy.arange(4).reshape(2,2) >>> a array([[0, 1],        [2, 3]]) >>> a[None] array([[[0, 1],         [2, 3]]]) 

Is this behavior intentional or a side-effect? If intentional, is there some rationale for it?

like image 454
Paul Avatar asked Sep 10 '09 23:09

Paul


People also ask

What does [: None mean in numpy?

None is an alias for NP. newaxis. It creates an axis with length 1. This can be useful for matrix multiplcation etc. >>>> import numpy as NP >>>> a = NP.arange(1,5) >>>> print a [1 2 3 4] >>>> print a.shape (4,) >>>> print a[:,None].shape (4, 1) >>>> print a[:,None] [[1] [2] [3] [4]]

Can numpy array have none?

No, it is an array of Nones. It is an array of exactly one None.

What does slice none do?

Above, slice(9) returns the slice object as slice(None, 9, None) , which you can pass to any iterable object to get that index portion. The slice() method can be used with string, list, tuple, set, bytes, or range. The following example fetch the portion of the list object.

Can you slice numpy arrays?

As with indexing, the array you get back when you index or slice a numpy array is a view of the original array. It is the same data, just accessed in a different order. This is different to lists, where a slice returns a completely new list.


1 Answers

Using None is equivalent to using numpy.newaxis, so yes, it's intentional. In fact, they're the same thing, but, of course, newaxis spells it out better.

The docs:

The newaxis object can be used in all slicing operations to create an axis of length one. newaxis is an alias for ‘None’, and ‘None’ can be used in place of this with the same result.

A related SO question.

like image 164
tom10 Avatar answered Oct 04 '22 21:10

tom10