第四课 Pandas时序型数据分析
第六节 时序数据滑动窗口操作
import pandas as pd
import numpy as np
ser_obj = pd.Series(np.random.randn(1000),
index=pd.date_range('20190101', periods=1000))
ser_obj = ser_obj.cumsum()
ser_obj.head()
2019-01-01 0.470424
2019-01-02 2.462145
2019-01-03 2.365791
2019-01-04 3.063709
2019-01-05 3.203847
Freq: D, dtype: float64
rolling_obj = ser_obj.rolling(window=3)
print(rolling_obj)
Rolling [window=3,center=False,axis=0]
rolling_obj.mean().head()
2019-01-01 NaN
2019-01-02 NaN
2019-01-03 1.766120
2019-01-04 2.630548
2019-01-05 2.877782
Freq: D, dtype: float64
# 验证:
# 0-3数据的均值
print(ser_obj[0:3].mean())
# 1-4数据的均值
print(ser_obj[1:4].mean())
1.7661196493723095
2.6305481975203295
# 画图查看
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(15, 5))
ser_obj.loc['2019-01':'2019-03'].plot(style='r--')
# ser_obj.rolling(window=10, center=False).mean().plot(style='g')
ser_obj.loc['2019-01':'2019-03'].rolling(window=10, center=True).mean().plot(style='b')
ser_obj.loc['2019-01':'2019-03'].rolling(window=5, center=True).mean().plot(style='g')
<matplotlib.axes._subplots.AxesSubplot at 0x2a960364b88>
ser_obj = pd.Series(range(10))
ser_obj
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
dtype: int64
ser_obj.rolling(window=3).sum()[5]
12.0
ser_obj.rolling(window=3, center=True).mean()[5]
5.0
pandas-滑动窗口
最新推荐文章于 2024-01-23 09:52:54 发布