M乘N形状的滑动窗口numpy.ndarray [英] sliding window of M-by-N shape numpy.ndarray

查看:147
本文介绍了M乘N形状的滑动窗口numpy.ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为(6,2)的numpy数组

I have a numpy array of shape (6,2)

[[00,01],
 [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 likes this:

[[00,01,10,11,20,21],
 [10,11,20,21,30,31],
 [20,21,30,31,40,41],
 [30,31,40,41,50,51]]

我正在寻找一个麻木的解决方案.如果您的解决方案可以参数化原始数组的形状以及窗口大小和步长大小,那就太好了.

I'm looking for a numpy solution. If your solution could parametrize the the shape of the original array as well as the window size and step size, that'd great.

我找到了这个相关的答案使用跨度获得有效的移动平均滤波器,但我看不到如何在其中指定步长以及如何将窗口从3d折叠到连续的2d数组.也是在Python中滚动或滑动窗口迭代器,但这在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 in Python 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆