簡體   English   中英

時間序列數據的滑動窗口

[英]sliding window on time series data

我在python 3.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_

但是,如果首先使用numpy數組輸入而不是使用np.asarray ,而您想要的只是一個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_

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM