Python 时间序列数据的滑动窗口

Python 时间序列数据的滑动窗口,python,numpy,Python,Numpy,我在Python3.5上有一个滑动窗口,它用于长时间序列数据,到目前为止我有很好的结果,但我只需要确定我的滑动窗口是否工作正常。因此我决定在一个简单的数据上进行测试,如图所示 import numpy as np import itertools as it x=[1,2,3,4,5,6,7,8,9] def moving_window(x, length, step=1): streams = it.tee(x, length) return zip(*[it.islice(

我在Python3.5上有一个滑动窗口,它用于长时间序列数据,到目前为止我有很好的结果,但我只需要确定我的滑动窗口是否工作正常。因此我决定在一个简单的数据上进行测试,如图所示

import  numpy as np
import itertools as it
x=[1,2,3,4,5,6,7,8,9]
def moving_window(x, length, step=1):
    streams = it.tee(x, length)
    return zip(*[it.islice(stream, i, None, step) for stream, i in zip(streams, it.count(step=step))])
x_=list(moving_window(x, 3))
x_=np.asarray(x_)
print(x_)
我的打印结果是

[1 2 3][2 3 4][3 4 5][4 5 6][5 6 7][6 7 8][7 8 9]

我希望我的输出看起来像

[1 2 3][4 5 6][7 8 9]

所以我试着把步数设为3,但是我得到了

[[1 4 7]]

看起来这些步骤也出现在幻灯片内容中,而不仅仅是在幻灯片之间,我如何才能得到我想要的结果

import  numpy as np
import itertools as it
x=[1,2,3,4,5,6,7,8,9]
def moving_window(x, length, step=1):
    streams = it.tee(x, length)
    return zip(*[it.islice(stream, i, None, step*length) for stream, i in zip(streams, it.count(step=step))])
x_=list(moving_window(x, 3))
x_=np.asarray(x_)
print(x_)

您需要有
it.islice(stream,i,None,step*length)
对于您想要的输出

似乎可以有一种更简单的方法来实现您想要做的事情。您可以简单地使用python
range
函数生成所需的索引,如下所示

import numpy as np

def moving_window(x, length):
    return [x[i: i + length] for i in range(0, (len(x)+1)-length, length)]

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x_ = moving_window(x, 3)
x_ = np.asarray(x_)
print x_
但是,如果不是使用
np.asarray
一个numpy数组输入首先是可以接受的,而您所需要的只是一个2D窗口输出(基本上只是一个矩阵),那么您的问题就相当于重塑一个数组

import numpy as np

def moving_window(x, length):
    return x.reshape((x.shape[0]/length, length))

x = np.arange(9)+1      # numpy array of [1, 2, 3, 4, 5, 6, 7, 8, 9]
x_ = moving_window(x, 3)
print x_