将Numpy数组索引存储在变量中 [英] 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]
显然这是行不通的,并且显然在这种特殊情况下,可能还有其他方法可以做到这一点,但是假设我真的想要这样做,我该如何使用变量来切片一个numpy的数组?
Obviously this will not work, and obviously in this particular case there might be other ways to do this, but supposing I really want to do stuff this way, how can I use a variable to slice a numpy array?
推荐答案
np.lib.index_tricks
具有许多可以简化索引编制的函数(和类). np.s_
是这样的功能之一.它实际上是具有__get_item__
方法的类的实例,因此它使用所需的[]
表示法.
np.lib.index_tricks
has a number of functions (and classes) that can streamline indexing. np.s_
is one such function. It is actually an instance of a class that has a __get_item__
method, so it uses the []
notation that you want.
使用说明:
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用于最后结果的临时变量.
Notice that it constructs the same tuple of slices that ajcr
did.
_
is the temporary variable that IPython uses for the last result.
要将此类元组传递给函数,请尝试:
To pass such a tuple to a function, try:
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)
这篇关于将Numpy数组索引存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!