简体   繁体   中英

sliding window on time series data

I have a sliding window on python 3.5 which am using on a long time series data,so far I have good results but I just need to be sure if my sliding window is working properly.So I decided to test on a simple data as can be seen here.

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_)

my printout results are

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

i want my output to look like

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

so I tried to put a step of 3,but instead I get

[[1 4 7]]

looks like the steps also appear within the slide contents and not just between the slides,how can I get the result I want?

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_)

You need to have it.islice(stream, i, None, step*length) for the output you desire

It seems like there could be a simpler way to achieve what you're trying to do. You could simply generate the required indices using the python range function as follows;

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_

However if instead of using np.asarray a numpy array input is acceptable in the first place, and all you want is a 2D windowed output (essentially just a matrix), then your problem is equivalent to reshaping an array;

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_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM