Lee Lee - 4 months ago 21
Python Question

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?

Answer

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.
Comments