TSAP(5) : rolling & expanding

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014281392/article/details/83213024

TSAP : TimeSeries Analysis with Python

%matplotlib inline 
import matplotlib.pylab
import numpy as np
import pandas as pd

Window functions are like aggregation functions

df = pd.DataFrame(np.random.randn(300, 3), 
                  index = pd.date_range('7/1/2016', freq = 'D',periods = 300),
                  columns = ['A', 'B', 'C'])

df.head()
A B C
2016-07-01 1.251741 -0.669649 0.845530
2016-07-02 -1.065566 0.399674 -0.034806
2016-07-03 -0.990938 -0.214281 -1.890150
2016-07-04 2.084868 1.041457 0.924540
2016-07-05 1.762719 -1.435734 -1.234330
#pd.rolling_mean(df, window = 2)[1:10] # in future versions you want to resample separately
r = df.rolling(window = 50)
#r.agg, r.apply, r.count, r.exclusions,
#r.max, r.median, r.name, r.quantile,
#r.kurt, r.cov, r.corr, r.aggregate, 
# r.std, r.skew, r.sum, r.var
df.plot( figsize=(10,4))
r.mean().plot(figsize=(10,4))
#exponentially weighted(指数加权)
df.ewm(min_periods=2, adjust=True, span=50, ignore_na=False).mean().plot(figsize=(10,4))

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

# 累计求和
df = df.cumsum()

df.rolling(window = 50).sum().plot(figsize=(10,4), title='cumsum')

在这里插入图片描述

# 自定义函数
df.rolling(window =50).apply(lambda x: np.fabs(x - x.mean()).mean()).plot(figsize=(10,4))

在这里插入图片描述

df.head()
A B C
2016-07-01 1.251741 -0.669649 0.845530
2016-07-02 0.186175 -0.269975 0.810724
2016-07-03 -0.804764 -0.484257 -1.079426
2016-07-04 1.280105 0.557200 -0.154886
2016-07-05 3.042824 -0.878534 -1.389216

Expanding windows

截止每个时间点累计求和的平均值


df.expanding(min_periods = 1).mean().plot(figsize=(10,4))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u014281392/article/details/83213024
今日推荐