0
0
Pandasdata~5 mins

rolling() for moving windows in Pandas

Choose your learning style9 modes available
Introduction

We use rolling windows to look at a small part of data at a time. This helps us find trends or patterns that change over time.

To calculate the average temperature over the last 7 days to see weather trends.
To find the moving average of stock prices to understand market trends.
To smooth noisy data like sensor readings by averaging recent values.
To calculate the sum of sales in the last month for each day.
To detect sudden changes by comparing recent data points.
Syntax
Pandas
DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None)

window is the size of the moving window (number of rows or offset).

min_periods is the minimum number of observations in the window required to have a value.

Examples
Calculate the moving average over the last 3 rows.
Pandas
df['value'].rolling(window=3).mean()
Calculate the moving sum over the last 5 rows, but allow results even if less than 5 rows are available.
Pandas
df['value'].rolling(window=5, min_periods=1).sum()
Calculate the moving average with the window centered on the current row.
Pandas
df.rolling(window=4, center=True).mean()
Sample Program

This code creates a table of sales for 7 days. Then it calculates the average sales for each day and the two days before it (3-day window). The first two days have no full window, so their result is NaN.

Pandas
import pandas as pd

data = {'day': [1, 2, 3, 4, 5, 6, 7], 'sales': [10, 20, 30, 40, 50, 60, 70]}
df = pd.DataFrame(data)

# Calculate 3-day moving average of sales
rolling_avg = df['sales'].rolling(window=3).mean()

print(rolling_avg)
OutputSuccess
Important Notes

If the window size is larger than the available data points, the result will be NaN unless you set min_periods lower.

You can use different functions like mean(), sum(), max(), and min() after rolling.

Setting center=True moves the window so it is centered on the current row instead of ending at it.

Summary

Rolling windows let you analyze data in small moving chunks.

Use rolling(window) followed by a function like mean() to get moving averages.

Adjust min_periods to control when results start appearing.