M×N 形状 numpy.ndarray 的滑动窗口
问题描述
我有一个形状为 (6,2) 的 Numpy 数组:
I have a Numpy array of shape (6,2):
[[ 0, 1],
[10,11],
[20,21],
[30,31],
[40,41],
[50,51]]
我需要一个步长为 1
和窗口大小为 3
的滑动窗口,如下所示:
I need a sliding window with step size 1
and window size 3
like this:
[[ 0, 1,10,11,20,21],
[10,11,20,21,30,31],
[20,21,30,31,40,41],
[30,31,40,41,50,51]]
我正在寻找一个 Numpy 解决方案.如果您的解决方案可以参数化原始数组的形状以及窗口大小和步长,那就太好了.
I'm looking for a Numpy solution. If your solution could parametrise the shape of the original array as well as the window size and step size, that'd be great.
我找到了这个相关的答案 Using strides for an effective move average filter 但我看不到如何在那里指定步长以及如何将窗口从 3d 折叠到连续的 2d 数组.还有这个 滚动或滑动窗口迭代器? 但那是在 Python 和我'不知道这有多有效.此外,它支持元素,但如果每个元素都有多个特征,它最终不会将它们连接在一起.
I found this related answer Using strides for an efficient moving average filter but I don't see how to specify the stepsize there and how to collapse the window from the 3d to a continuous 2d array. Also this Rolling or sliding window iterator? but that's in Python and I'm not sure how efficient that is. Also, it supports elements but does not join them together in the end if each element has multiple features.
解决方案
In [1]: import numpy as np
In [2]: a = np.array([[00,01], [10,11], [20,21], [30,31], [40,41], [50,51]])
In [3]: w = np.hstack((a[:-2],a[1:-1],a[2:]))
In [4]: w
Out[4]:
array([[ 0, 1, 10, 11, 20, 21],
[10, 11, 20, 21, 30, 31],
[20, 21, 30, 31, 40, 41],
[30, 31, 40, 41, 50, 51]])
你可以把它写成这样的函数:
You could write this in as a function as so:
def window_stack(a, stepsize=1, width=3):
n = a.shape[0]
return np.hstack( a[i:1+n+i-width:stepsize] for i in range(0,width) )
<小时>
这并不真正取决于原始数组的形状,只要 a.ndim = 2
.请注意,我从不在交互式版本中使用任何一种长度.形状的第二维无关紧要;每一行可以任意长.感谢@Jaime 的建议,您可以完全不检查形状:
This doesn't really depend on the shape of the original array, as long as a.ndim = 2
. Note that I never use either lengths in the interactive version. The second dimension of the shape is irrelevant; each row can be as long as you want. Thanks to @Jaime's suggestion, you can do it without checking the shape at all:
def window_stack(a, stepsize=1, width=3):
return np.hstack( a[i:1+i-width or None:stepsize] for i in range(0,width) )
相关文章