Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: arr[...,0,:] works. But how do I store the data contained in the slice command (..., 0, :)?

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.

like image 590
Chironex Avatar asked Jul 22 '11 20:07

Chironex


4 Answers

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))
like image 118
Thomas Wouters Avatar answered Nov 08 '22 17:11

Thomas Wouters


Use s_ in NumPy:

In [1]: np.s_[...,0,:]
Out[1]: (Ellipsis, 0, slice(None, None, None))
like image 44
HYRY Avatar answered Nov 08 '22 17:11

HYRY


The equivalent to (...,0,:) should be...

>>> myslice = (..., 0, slice(None, None))
>>> myslice
(Ellipsis, 0, slice(None, None, None))
like image 3
JAB Avatar answered Nov 08 '22 17:11

JAB


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)
like image 3
Karl Knechtel Avatar answered Nov 08 '22 17:11

Karl Knechtel