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.
The syntax
[:, :2, :, :540]
is turned into a tuple ofslice
objects by Python: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:Then your dictionary of slices could be written as:
* technically
s_
is an alias for the classIndexExpression
that implements a special__getitem__
method.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
: