Is there a Pandas function to create a 7-day moving average from a time-series?

Viewed 5531

I'm looking for documentation or a tutorial to create a 7-day moving average from a time-series from Pandas on Python, and visualize it on Matplotlib.

Here's the my code:

import pandas as pd
import matplotlib.pyplot as plt 
from datetime import datetime, timedelta
plt.style.use('seaborn-poster')

url = 'https://raw.githubusercontent.com/mariorz/covid19-mx-time-series/master/data/covid19_confirmed_mx.csv'
df = pd.read_csv(url, index_col=0)

df = df.loc['Colima','18-03-2020':'12-08-2020']
df = pd.DataFrame(df)
df.index = pd.to_datetime(df.index, format='%d-%m-%Y')



fig, ax = plt.subplots()
ax.plot(df)
ax.set_ylabel('Casos positivos', fontsize=10)
ax.set_title('Casos positivos acumulados de COVID-19 en Colima (12 de agosto, 2020)', fontsize=10)
plt.xticks(rotation=30)
plt.savefig('positivos_registro.png', dpi=500)

Output: enter image description here

1 Answers

You can use .rolling() to calculate moving averages, like this:

df.rolling(window=7).mean() 

Rolling() also has an argument center=True to have the window calculated centred in the middle. Then it looks 3 days ahead and 3 days back when your window is 7.

The default value is center=False. It just takes current day value + 6 day values back when the window is 7.

Related