
We’ve learned how to group time by month (using group_by_dynamic), but what about calculating a “7-day moving average”? This is where Polars rolling functions can be incredibly useful for time series analysis.
This rolling window function calculates a value (like an average) over a “window” of n periods that “rolls” down your data. This is perfect for smoothing out noisy data to see the real trend.
The rolling() Method
In Polars, you use .rolling() inside an expression.
The Setup
Let’s create a DataFrame with 10 days of sales data.
import polars as pl
from datetime import date, timedelta
start_date = date(2025, 1, 1)
df = pl.DataFrame({
"date": [start_date + timedelta(days=i) for i in range(10)],
"sales": [10, 12, 15, 8, 11, 16, 20, 18, 22, 25]
})Calculating a 3-Day Rolling Average
We want to create a new column where each value is the average of itself and the 2 days prior.
# 'window_size=3' is the 3-day window
# 'by="date"' tells Polars which column to roll over
df_rolling = df.with_columns(
pl.col("sales")
.rolling("date", window_size="3d")
.mean()
.alias("3_day_avg")
)
print(df_rolling)Output:
shape: (10, 3) โโโโโโโโโโโโโโฌโโโโโโโโฌโโโโโโโโโโโโ โ date โ sales โ 3_day_avg โ โ --- โ --- โ --- โ โ date โ i64 โ f64 โ โโโโโโโโโโโโโโชโโโโโโโโชโโโโโโโโโโโโก โ 2025-01-01 โ 10 โ 10.0 โ โ 2025-01-02 โ 12 โ 11.0 โ โ 2025-01-03 โ 15 โ 12.333333 โ โ 2025-01-04 โ 8 โ 11.666667 โ โ 2025-01-05 โ 11 โ 11.333333 โ โ ... โ ... โ ... โ โโโโโโโโโโโโโโดโโโโโโโโดโโโโโโโโโโโโ
You can replace .mean() with .sum(), .max(), .min(), or .std() to calculate other rolling statistics.
Key Takeaways
- The article introduces how to calculate a 7-day moving average using Polars rolling functions.
- A rolling window function smooths out data by calculating averages over a set number of periods.
- The rolling() method in Polars allows for easy application of rolling calculations within expressions.
- The article provides a setup example with a DataFrame containing 10 days of sales data for context.
- You can use various functions like .mean(), .sum(), .max(), .min(), or .std() for different rolling statistics.





