Sliding window of M-by-N shape numpy.ndarray(MN 形状 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) )
这篇关于M×N 形状 numpy.ndarray 的滑动窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:M×N 形状 numpy.ndarray 的滑动窗口
基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
