Jzl5325 Jzl5325 - 8 days ago 6
Python Question

NumPy slice notation in a dictionary

I wonder if it is possible to store numpy slice notation in a python dictionary. Something like:

lookup = {0:[:540],
30:[540:1080],
60:[1080:]}


It is possible to use native python slice syntax, e.g.
slice(0,10,2)
, but I have not been able to store more complex slices. For example, something that is multidimensional
[:,:2,:, :540]
.

My current work around is to store the values as tuples and then unpack these into the necessary slices.

Working in Python 2.x.

Answer

The syntax [:, :2, :, :540] is turned into a tuple of slice objects by Python:

(slice(None, None, None),
 slice(None, 2, None),
 slice(None, None, None),
 slice(None, 540, None))

A convenient way to generate this tuple is to use the special function* np.s_. You just need to pass it the [...] expression. For example:

>>> np.s_[:540]
slice(None, 540, None)
>>> np.s_[:, :2, :, :540]
(slice(None, None, None),
 slice(None, 2, None),
 slice(None, None, None),
 slice(None, 540, None))

Then your dictionary of slices could be written as:

lookup = {0: np.s_[:540],
          30: np.s_[540:1080],
          60: np.s_[1080:]}

* technically s_ is an alias for the class IndexExpression that implements a special __getitem__ method.

Comments