圆形numpy数组索引 [英] circular numpy array indices
问题描述
我有一个n-n numpy数组 a = [1,2,3,4,5,6]
以及一个获取两个输入的函数, starting_index
和 ending_index
,并返回 a [staring_index:ending_index]
。
I have a 1-D numpy array a = [1,2,3,4,5,6]
and a function that gets two inputs, starting_index
and ending_index
, and returns a[staring_index:ending_index]
.
当 ending_index
小于 starting_index $ c $时,显然我遇到了麻烦C>。在这种情况下,函数应该从starting_index开始并以循环方式遍历向量
a
,即返回 starting_index <之后的所有元素/ code>加上从索引零到
ending_index
的所有元素。
Clearly I run into trouble when ending_index
is smaller than starting_index
. In this case, the function should start from the starting_index and traverse the vector a
in a circular way, i.e., return all the elements coming after starting_index
plus all the elements from index zero to ending_index
.
例如,如果 starting_index = 4
和 ending_index = 1
那么输出应该是 output = [5,6,1]
。我可以用 if
条件实现它,但我想知道是否有任何Pythonic和简洁的方法来做它?
For instance, if starting_index=4
and ending_index=1
then the output should be output = [5,6,1]
. I can implement it with an if
condition but I was wondering if there is any Pythonic and concise way to do it?
推荐答案
np.take
有一个换行
模式:
In [171]: np.take(np.arange(1,7),range(4,7),mode='wrap')
Out[171]: array([5, 6, 1])
那是不是你想要的。
实际上,模数做同样的事情
Actually, modulus does the same thing
In [177]: a[np.array([4,5,6])%6]
Out[177]: array([5, 6, 1])
但是将(4,1)
变为<的小函数如何? code> [4,5,6] ,或者如果你喜欢 [4,5,0]
?
But how about a small function that turns (4,1)
into [4, 5, 6]
, or if you prefer [4, 5, 0]
?
def foo(a, start, stop):
# fn to convert your start stop to a wrapped range
if stop<=start:
stop += len(a)
return np.arange(start, stop)%len(a)
a[foo(a,4,1)] # or
np.take(a,foo(a,4,1))
这篇关于圆形numpy数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!