In Numpy (and Python in general, I suppose), how does one store a slice-index, such as (...,0,:), in order to pass it around and apply it to various arrays? It would be nice to, say, be able to pass a slice-index to and from functions.
Python creates special objects out of the slice syntax, but only inside the square brackets for indexing. You can either create those objects by hand (in this case, (...,0,:)
is (Ellipsis, 0, slice(None, None, None))
, or you can create a little helper object:
class ExtendedSliceMaker(object):
def __getitem__(self, idx):
return idx
>>> ExtendedSliceMaker()[...,0,:]
(Ellipsis, 0, slice(None, None, None))
Use s_ in NumPy:
In [1]: np.s_[...,0,:]
Out[1]: (Ellipsis, 0, slice(None, None, None))
The equivalent to (...,0,:)
should be...
>>> myslice = (..., 0, slice(None, None))
>>> myslice
(Ellipsis, 0, slice(None, None, None))
The neat thing about Python is that you can actually make a class to inspect how these things are represented. Python uses the magic method __getitem__
to handle indexing operations, so we'll make a class that overloads this to show us what was passed in, instantiate the class, and "index in" to the instance:
class foo:
def __getitem__(self, index): print index
foo()[...,0,:]
And our result is:
(Ellipsis, 0, slice(None, None, None))
Ellipsis
and slice
are builtins, and we can read their documentation:
help(Ellipsis)
help(slice)
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