显示滚动平均
您也可以将时间序列中的值可视化为滚动平均。这相当于对数据进行"平滑"处理,尤其适用于时间序列中噪声或离群值较多的情况。对于给定的 DataFrame df,可以使用以下命令获得时间序列的滚动平均:
df_mean = df.rolling(window=12).mean()
window 参数应根据时间序列的粒度来设定。例如,如果时间序列是按天记录的数据,而您希望以整年为窗口计算滚动值,应将参数设为 window=365。此外,获取其他指标的滚动值也很容易,比如标准差(.std())或方差(.var())。
本练习是课程的一部分
用 Python 可视化时间序列数据
练习说明
- 计算
co2_levels的 52 周滚动均值,并将结果赋给ma。 - 计算
co2_levels的 52 周滚动标准差,并将结果赋给mstd。 - 计算时间序列的上界,定义为 滚动均值 + (2 × 滚动标准差),并将结果赋给
ma[upper]。同样,计算下界为 滚动均值 - (2 × 滚动标准差),并将结果赋给ma[lower]。 - 绘制
ma的折线图。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Compute the 52 weeks rolling mean of the co2_levels DataFrame
ma = ____.rolling(window=____).____()
# Compute the 52 weeks rolling standard deviation of the co2_levels DataFrame
mstd = ____
# Add the upper bound column to the ma DataFrame
ma['upper'] = ma['co2'] + (____ * ____)
# Add the lower bound column to the ma DataFrame
ma['lower'] = ma['co2'] - (____ * ____)
# Plot the content of the ma DataFrame
ax = ____(linewidth=0.8, fontsize=6)
# Specify labels, legend, and show the plot
ax.set_xlabel('Date', fontsize=10)
ax.set_ylabel('CO2 levels in Mauai Hawaii', fontsize=10)
ax.set_title('Rolling mean and variance of CO2 levels\nin Mauai Hawaii from 1958 to 2001', fontsize=10)
plt.show()