NumPy slice notation in a dictionary

2019-06-17 10:14发布

问题:

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.

回答1:

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.



回答2:

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.