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 的滑动窗口
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
