问题
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.
回答1:
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))
回答2:
Use s_ in NumPy:
In [1]: np.s_[...,0,:]
Out[1]: (Ellipsis, 0, slice(None, None, None))
回答3:
The equivalent to (...,0,:)
should be...
>>> myslice = (..., 0, slice(None, None))
>>> myslice
(Ellipsis, 0, slice(None, None, None))
回答4:
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)
回答5:
I think you want to just do myslice = slice(1,2) to for example define a slice that will return the 2nd element (i.e. myarray[myslice] == myarray[1:2])
来源:https://stackoverflow.com/questions/6795657/numpy-arr-0-works-but-how-do-i-store-the-data-contained-in-the-slice-co