Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
Jzl5325 Avatar asked May 14 '15 18:05

Jzl5325


2 Answers

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.

like image 140
Alex Riley Avatar answered Sep 18 '22 13:09

Alex Riley


Numpy has a lot of Indexing routines .And in this case you can use the following functions for Generating index arrays :

c_ : Translates slice objects to concatenation along the second axis.

r_ : Translates slice objects to concatenation along the first axis.

s_ : A nicer way to build up index tuples for arrays.

You can also use numpy.unravel_index :

Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.

like image 38
Mazdak Avatar answered Sep 20 '22 13:09

Mazdak