简体   繁体   English

如何从 numpy 数组中提取居中的 window?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM