calculate a rolling average in python

To calculate a rolling average in Python, we can use the pandas library which provides an easy-to-use rolling function that can be applied to a DataFrame or Series.

main.py
import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6], 'B': [10, 20, 30, 40, 50, 60]})

# Calculate rolling average on column A with window size 3
df['rolling_avg'] = df['A'].rolling(window=3).mean()

print(df)
249 chars
10 lines

In this code, we first import pandas library. Then, we create a sample dataframe with two columns A and B. We use the "rolling" function to calculate the rolling average on column A with a window size of 3. Finally, we add a new column called "rolling_avg" to the dataframe which contains the rolling average values.

The output of this code would be:

main.py
   A   B  rolling_avg
0  1  10          NaN
1  2  20          NaN
2  3  30          2.0
3  4  40          3.0
4  5  50          4.0
5  6  60          5.0
154 chars
8 lines

Note that, since we used a window size of 3, the first two rows of the "rolling_avg" column have a value of NaN, since there are not enough values in the window to calculate the rolling average.

gistlibby LogSnag