我有一个简单的时间序列,我正在努力估计移动窗口内的方差。更具体地说,我无法弄清楚与实现滑动窗口函数的方式有关的一些问题。例如,当使用 NumPy 且窗口大小 = 20 时:
def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
rolling_window(data, 20)
np.var(rolling_window(data, 20), -1)
datavar=np.var(rolling_window(data, 20), -1)
也许我在某个地方犯了错误,在这个思路上。
有谁知道一个简单的方法来做到这一点?
任何帮助/建议将非常受欢迎。
熊猫rolling_mean
and rolling_std
函数已被弃用并被更通用的“滚动”框架取代。 @elyase 的示例可以修改为:
import pandas as pd
import numpy as np
%matplotlib inline
# some sample data
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)).cumsum()
#plot the time series
ts.plot(style='k--')
# calculate a 60 day rolling mean and plot
ts.rolling(window=60).mean().plot(style='k')
# add the 20 day rolling standard deviation:
ts.rolling(window=20).std().plot(style='b')
The rolling
函数支持多种不同的窗口类型,如文档所示here https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html。可以调用许多函数rolling
对象,包括var
和其他有趣的统计数据(skew
, kurt
, quantile
, ETC。)。我一直坚持std
因为该图与平均值在同一个图表上,这从单位角度更有意义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)