python-pandas重采样与滑动窗口
为提高数据的可读性,我们常常在数据分析时用到重采样与滑动窗口,让数据尽力接近于真实值。
代码
#时间重采样,降采样,升采样
rng = pd.date_range('1/1/2011',periods=90,freq='D')
ts = pd.Series(np.random.randn(len(rng)),index=rng)
ts.resample('M').sum()
ts.resample('3D').sum()
day3Ts = ts.resample('3D').mean()
print(day3Ts)
#降采样,ffill bfill interpolate
print(day3Ts.resample('D').asfreq())
print(day3Ts.resample('D').ffill(2))
print(day3Ts.resample('D').interpolate('linear'))
#滑动窗口
df = pd.Series(np.random.randn(600),index = pd.date_range('7/1/2006',freq='D',periods=600))
print(df.head())
r = df.rolling(window =10)
#r.max ,r.median,r.std,r.skew,r.sum,r.var
print(r.mean())
#图展示
import matplotlib.pyplot as plt
plt.figure(figsize=(15,5))
df.plot(style = 'r--')
df.rolling(window=10).mean().plot(style='b')
plt.show()
总结
为了提升数据的准确性,将某个点的取值扩大到包含这个点的一段区间,用区间来进行判断,这个区间就是窗口。