[英]How can I extract a centered window from a numpy array?
Suppose I have the following numpy array:假设我有以下 numpy 数组:
>>> a = np.arange(0,21,1)
>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
Now suppose that I want to pick a window of length N
, where 2 < N <= a.shape[0]
, such that the window is "centered" around one of the elements of the array a
.现在假设我想选择一个长度为
N
的 window ,其中2 < N <= a.shape[0]
,这样 window 围绕数组a
元素“居中”。 For example, if I want to center a window of length N = 5
around the element 10
in array a
, then this window would be:例如,如果我想将长度为
N = 5
的 window 围绕数组a
中的元素10
居中,那么这个 window 将是:
>>> idx = 10 # index of the array element 10
>>> N = 5 # window size
>>> a[idx - N//2:idx + N//2 + 1]
array([ 8, 9, 10, 11, 12])
This method generalizes well for windows that are not near the edges of the array, but I can't make it work otherwise.此方法适用于不在阵列边缘附近的 windows,但我无法使其正常工作。 For example, if I want to extract a window of length
N = 7
around the element 2
in a
, then what I get is:例如,如果我想在
a
中的元素2
周围提取长度为N = 7
的 window ,那么我得到的是:
>>> idx = 2
>>> N = 7
>>> a[idx - N//2:idx + N//2 + 1]
array([], dtype=int32)
However what I want is:但是我想要的是:
>>> a[0:7]
array([0, 1, 2, 3, 4, 5, 6])
How can I generalize this method for windows near the edges of a
?我如何将这种方法推广到 windows
a
边缘附近?
Try with:尝试:
idx = 2
start = min(idx - N//2, 0)
a[start:start + N]
Note that this is not centered at idx=2
.请注意,这不是以
idx=2
为中心。
Based on Quang Hoang's answer , here is what worked:根据Quang Hoang 的回答,以下是有效的:
import numpy as np
a = np.arange(0,21,1)
idx = 5 # desired element index
N = 7 # window length
if N % 2: # if window length is odd
step = N // 2
else: # if window length is even
step = int(N/2 - 1)
# make sure starting index is between 0 and a.shape[0] - N
start = min(max(idx-step,0),a.shape[0] - N)
window = a[start:start + N]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.