Exibir médias móveis
Também é possível visualizar médias móveis dos valores na sua série temporal. Isso equivale a “suavizar” seus dados e pode ser especialmente útil quando a série contém muito ruído ou outliers. Para um DataFrame df, você pode obter a média móvel da série temporal usando o comando:
df_mean = df.rolling(window=12).mean()
O parâmetro window deve ser definido de acordo com a granularidade da sua série temporal. Por exemplo, se sua série tem dados diários e você quer valores móveis ao longo de um ano inteiro, defina window=365. Além disso, é fácil obter valores móveis para outras métricas, como o desvio padrão (.std()) ou a variância (.var()).
Este exercício faz parte do curso
Visualizing Time Series Data in Python
Instruções do exercício
- Calcule a média móvel de 52 semanas de
co2_levelse atribua ama. - Calcule o desvio padrão móvel de 52 semanas de
co2_levelse atribua amstd. - Calcule o limite superior da série temporal, definido como média móvel + (2 * desvio padrão móvel), e atribua a
ma[upper]. Da mesma forma, calcule o limite inferior como média móvel - (2 * desvio padrão móvel) e atribua ama[lower]. - Plote o gráfico de linhas de
ma.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# 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()