Store Numpy array index in variable

I want to pass an index slice as an argument to a function:

def myfunction(some_object_from_which_an_array_will_be_made, my_index=[1:5:2,::3]):
    my_array = whatever(some_object_from_which_an_array_will_be_made)
    return my_array[my_index]

Obviously, this will not work, and obviously, in this particular case there may be other ways to do this, but assuming that I really want to do so, how can I use a variable to slice a numpy array?

+4
source share
2 answers

np.lib.index_trickshas a number of functions (and classes) that can optimize indexing. np.s_- one of these functions. This is actually an instance of the class that the method has __get_item__, so it uses the notation []you want.

Illustration of its use:

In [249]: np.s_[1:5:2,::3]
Out[249]: (slice(1, 5, 2), slice(None, None, 3))

In [250]: np.arange(2*10*4).reshape(2,10,4)[_]
Out[250]: 
array([[[40, 41, 42, 43],
        [52, 53, 54, 55],
        [64, 65, 66, 67],
        [76, 77, 78, 79]]])

In [251]: np.arange(2*10*4).reshape(2,10,4)[1:5:2,::3]
Out[251]: 
array([[[40, 41, 42, 43],
        [52, 53, 54, 55],
        [64, 65, 66, 67],
        [76, 77, 78, 79]]])

, , ajcr. _ - , IPython .

, :

def myfunction(some_object_from_which_an_array_will_be_made, my_index=np.s_[:,:]):
    my_array = whatever(some_object_from_which_an_array_will_be_made)
    return my_array[my_index]
I = np.s_[1:5:2,::3]
myfunction(obj, my_index=I)
+4

- slice ( slice) , .

,

my_array[1:5:2, ::3]

my_array[slice(1,5,2), slice(None,None,3)]

, :

def myfunction(some_object, my_index=(slice(1,5,2), slice(None,None,3))):
    my_array = whatever(some_object)
    return my_array[my_index]
+1

All Articles