将Numpy数组索引存储在变量中

The*_*era 7 python arrays numpy

我想将索引切片作为参数传递给函数:

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]
Run Code Online (Sandbox Code Playgroud)

显然这不起作用,显然在这种特殊情况下可能有其他方法可以做到这一点,但假设我真的想用这种方式做事,我怎样才能使用变量来切割numpy数组呢?

hpa*_*ulj 8

np.lib.index_tricks有许多可以简化索引的函数(和类). np.s_就是这样一个功能.它实际上是一个具有__get_item__方法的类的实例,因此它使用[]您想要的符号.

它的用途说明:

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]]])
Run Code Online (Sandbox Code Playgroud)

请注意,它构造了相同的切片元组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)
Run Code Online (Sandbox Code Playgroud)