在Python/numpy中环绕切片 [英] wrapping around slices in Python / numpy
问题描述
我有一个numpy数组,我想获得第i个点的邻居".通常,我使用的数组是二维的,但是下面的一维示例说明了我要查找的内容.如果
I have a numpy array, and I want to get the "neighbourhood" of the i'th point. Usually the arrays I'm using are two-dimensional, but the following 1D example illustrates what I'm looking for. If
A = numpy.array([0,10,20,30,40,50,60,70,80,90])
则元素4的(大小5)邻域为[20,30,40,50,60]
,这可以通过执行A[i-2:i+3]
轻松获得.
Then the (size 5) neighbourhood of element 4 is [20,30,40,50,60]
, and this can easily be obtained by doing A[i-2:i+3]
.
但是,我还需要邻域来环绕"数组的边缘,以使元素0的邻域为[80,90,0,10,20]
,元素9的邻域为[70,80,90,0,10]
.我似乎找不到一种完美的方法来执行此操作,因此每次出现这种情况时,我最终都不得不使用一些复杂而烦人的逻辑(这对我来说是很常见的).在二维情况下,一个点的邻域将是一个矩形阵列.
However, I also need the neighbourhoods to "wrap around" the edges of the array, so that the neighbourhood of the element 0 is [80,90,0,10,20]
and the neighbourhood of the element 9 is [70,80,90,0,10]
. I can't seem to find an elegant way to do this, so I end up having to use some complicated, annoying logic every time this comes up (which is very often for me). In the 2D case the neighbourhood of a point would be a rectangular array.
所以我的问题是,是否有一种整洁的方法来表示这种numpy中的环绕式邻居"操作?我希望返回的是切片而不是副本,但是可读性和速度是最重要的考虑因素.
So my question is, is there a neat way to expres this "wrap-around neighbourhood" operation in numpy? I would prefer something that returns a slice rather than a copy, but readability and speed are the most important considerations.
推荐答案
numpy.take
在'wrap'
模式下将使用您的索引以数组的长度为模.
numpy.take
in 'wrap'
mode will use your indices modulo the length of the array.
indices = range(i-2,i+3)
neighbourhood = A.take(indices, mode='wrap')
有关详细信息,请参见文档 numpy.take
See documentation for details numpy.take
这篇关于在Python/numpy中环绕切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!