NumPy slice notation in a dictionary

房东的猫 提交于 2019-12-23 08:47:59

问题


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.



来源:https://stackoverflow.com/questions/30244731/numpy-slice-notation-in-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!