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.
rolling() for moving windows in 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.
df['value'].rolling(window=3).mean()
df['value'].rolling(window=5, min_periods=1).sum()
df.rolling(window=4, center=True).mean()
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.
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)
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.
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.