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?
None is an alias for NP. newaxis. It creates an axis with length 1. This can be useful for matrix multiplcation etc.
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.
You can slice a numpy array is a similar way to slicing a list - except you can do it in more than one dimension.
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 .
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 outputslice(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. 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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With