Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon, None, slice(None) in numpy array indexers

As for a = np.arange(24).reshape(2,3,4)

a[0,:,1] or a[0,slice(None),1] outputs array([1, 5, 9])

while a[0,None,1] gives array([[4, 5, 6, 7]])

Could sb explain the latter?

like image 614
ddzzbbwwmm Avatar asked Jul 05 '16 16:07

ddzzbbwwmm


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.

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?

You can slice a numpy array is a similar way to slicing a list - except you can do it in more than one dimension.

How do I slice rows in NumPy?

Slice Two-dimensional Numpy Arrays To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .


2 Answers

Using a raw None (not in slice) is the same thing as using np.newaxis, of which it is but an alias.

In your case:

  • a[0,None,1] is like a[0,np.newaxis,1], hence the output
  • whereas slice(None) is like "slice nothing", which is why a[0,:,1] is the same as a[0,slice(None),1]. See numpy's Indexing doc.
like image 106
Tttt1228 Avatar answered Sep 18 '22 09:09

Tttt1228


a[0,None,1] is the same as a[0, 1] but with an extra axis in the result.

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

So a[0,None,1] is the same as a[0,np.newaxis,1]

In this case, where None is placed is not of relevance, but every None adds a new axis.

>>> a[0,None, 1]
array([[4, 5, 6, 7]])
>>> a[None,None,0,1]
array([[[4, 5, 6, 7]]])
>>> a[0,np.newaxis,1]
array([[4, 5, 6, 7]])
like image 25
Moses Koledoye Avatar answered Sep 17 '22 09:09

Moses Koledoye