ComenzarEmpieza gratis

Mostrar medias móviles

También puedes visualizar medias móviles de los valores de tu serie temporal. Esto equivale a “suavizar” tus datos y puede ser especialmente útil cuando tu serie temporal tiene mucho ruido o valores atípicos. Para un DataFrame df, puedes obtener la media móvil de la serie temporal con el comando:

df_mean = df.rolling(window=12).mean()

El parámetro window debe ajustarse según la granularidad de tu serie temporal. Por ejemplo, si tu serie contiene datos diarios y quieres valores móviles sobre un año completo, deberías especificar window=365. Además, es fácil obtener valores móviles para otras métricas, como la desviación estándar (.std()) o la varianza (.var()).

Este ejercicio forma parte del curso

Visualización de datos temporales en Python

Ver curso

Instrucciones del ejercicio

  • Calcula la media móvil de 52 semanas de co2_levels y asígnala a ma.
  • Calcula la desviación estándar móvil de 52 semanas de co2_levels y asígnala a mstd.
  • Calcula el límite superior de la serie temporal, definido como la media móvil + (2 * desviación estándar móvil), y asígnalo a ma[upper]. Del mismo modo, calcula el límite inferior como la media móvil - (2 * desviación estándar móvil) y asígnalo a ma[lower].
  • Dibuja el gráfico de líneas de ma.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# 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()
Editar y ejecutar código