moving average in pandas in python

To calculate the moving average of a time series data in pandas, we can use the rolling method which creates a rolling window of the desired time frame and applies a function to the data. In this case, we will apply the mean function to the window to calculate the moving average.

Here's an example:

main.py
import pandas as pd

# create a time series dataframe
data = {
    'date': ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'],
    'value': [10, 20, 30, 40, 50]
}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

# create a rolling window and calculate the moving average
window_size = 3
rolling_avg = df.rolling(window_size).mean()

print(rolling_avg)
423 chars
17 lines

Output:

main.py
            value
date             
2021-01-01    NaN
2021-01-02    NaN
2021-01-03   20.0
2021-01-04   30.0
2021-01-05   40.0
126 chars
8 lines

In the example above, we create a dataframe with a time series data and set the date column as the index (the set_index method with inplace=True modifies the dataframe in place). We then specify a window size of 3 and calculate the rolling average using the rolling method with the mean function applied to the window. The resulting dataframe contains the moving average values.

gistlibby LogSnag