In Polars, the rolling_mean() function is used to compute the rolling (or moving) average over a window of values in a Series. It’s especially useful for smoothing fluctuations in time series data or identifying trends over recent observations. The method works by applying a sliding window of a specified size and computing the average of the values within each window as it progresses through the Series.
In this article, I will explain the Polars Series rolling_mean() method, covering its syntax, parameters, and usage, and demonstrating how it returns a new Series with the calculated rolling (moving) average values.
Key Points –
- Calculates the moving (rolling) average of values over a specified window size.
- The
window_sizeparameter defines how many consecutive values to include in each average calculation. - Supports optional
weightsto compute a weighted rolling mean instead of a simple average. - Returns a new
Seriesof floating-point values representing the rolling means. - Produces
nullvalues for positions where the full window cannot be applied. - By default, results are aligned with the right edge of the window; setting
center=Truealigns results with the window center.
<a id="h-syntax-of-polars-series-rolling-mean-method"></a>
Syntax of Polars Series rolling_mean() Method
Let’s know the syntax of the series rolling_mean() method.
# Syntax of series rolling_mean()
Series.rolling_mean(
window_size: int,
weights: list[float] | None = None,
*,
min_samples: int | None = None,
center: bool = False,
) → Series[source]
<a id="h-parameters-of-the-polars-series-rolling-mean"></a>
Parameters of the Polars series rolling_mean()
The following are the parameters of the polars Series rolling_mean() method
window_size(int) - Size of the moving window (number of elements to include in each mean calculation).weights(list of float, optional) - Custom weights to apply to the elements in the window. Must be the same length aswindow_size. Defaults to equal weights.min_samples(int, optional) - Minimum number of non-null values required to compute a mean. If not enough, result will benull.center(bool, default=False) - Whether to align the result at the center of the window. By default, it aligns to the right edge.
<a id="h-return-value"></a>
Return Value
This function returns a new Series containing the rolling (moving) mean values.
<a id="h-usage-of-polars-series-rolling-mean-method"></a>
Usage of Polars Series rolling_mean() Method
The rolling_mean() function in Polars computes the average of values within a sliding window of a specified size along a Series. It’s commonly used to smooth data or identify trends in time series or numerical datasets.
Now, let’s create a Polars series using a list of values and use the rolling_mean() function.
import polars as pl
ser = pl.Series("numbers", [2, 4, 6, 8, 10])
print("Original Series:\n", ser)
Yields below output.
To calculate a simple rolling mean (moving average) with a window size of 3 on your Polars Series, you can use the rolling_mean() method.
# Rolling mean with window size 3
ser2 = ser.rolling_mean(window_size=3)
print("Rolling mean with window size 3:\n", ser2)
Here,
- The first two positions are
nullbecause there aren’t enough values to fill the window of size 3. - Starting from the 3rd value, it computes the mean of the current and previous two values, e.g.,
(2+4+6)/3= 4.0.
<a id="h-rolling-mean-with-window-size-2-centered"></a>
Rolling Mean with Window Size 2, Centered
To calculate a centered rolling mean with a window size of 2 in Polars, use the rolling_mean() method with window_size=2 and center=True.
# Rolling mean with window size 2, centered
ser2 = ser.rolling_mean(window_size=2, center=True)
print("Centered rolling mean with window size 2:\n", ser2)
# Output:
# Centered rolling mean with window size 2:
# shape: (5,)
# Series: 'numbers' [f64]
# [
# null
# 3.0
# 5.0
# 7.0
# 9.0
# ]
Here,
center=True means the window is centered around each element (spreading before and after, if possible).- For a window size of 2, since there's no clear center, Polars computes the average over the current and one adjacent value, trying to balance the position.
- This behavior makes it slightly different from uncentered (default) rolling means, and results may vary depending on edge-handling.
<a id="h-rolling-mean-with-custom-weights"></a>
Rolling Mean with Custom Weights
To compute a rolling mean with custom weights in Polars, use the rolling_mean() function along with the weights parameter.
# Custom weights (for window size 3, for example)
weights = [0.1, 0.3, 0.6] # Must sum to 1 (not mandatory but typical for weighted averages)
ser2 = ser.rolling_mean(window_size=3, weights=weights)
print("Rolling mean with custom weights:\n", ser2)
# Output:
# Rolling mean with custom weights:
# shape: (5,)
# Series: 'numbers' [f64]
# [
# null
# null
# 5.0
# 7.0
# 9.0
# ]
Here,
- The weighted mean is calculated like this for position 2;
(2×0.2) + (4×0.3) + (6×0.5) = 0.4 + 1.2 + 3.0=4.6 - The first two values are
nullbecause a full window of 3 values is required.
<a id="h-rolling-mean-on-floating-point-series"></a>
Rolling Mean on Floating Point Series
You can easily compute a rolling mean on a floating-point Polars Series using the same approach.
import polars as pl
# Create a floating-point Series
ser = pl.Series("floats", [2.5, 4.0, 6.7, 8.3, 10.1])
# Calculate rolling mean with window size 3
ser2 = ser.rolling_mean(window_size=3)
print("Rolling mean on floating-point series:\n", ser2)
# Output:
# Rolling mean on floating-point series:
# shape: (5,)
# Series: 'floats' [f64]
# [
# null
# null
# 4.4
# 6.333333
# 8.366667
# ]
Here,
- The first two values are
nullbecause there aren’t enough elements to fill a window of size 3. - After that, the mean is computed over each sliding window of 3 values (e.g., for index 2: mean of
[2.5, 4.0, 6.7]= 4.4).
<a id="h-rolling-mean-on-a-series-with-null-values"></a>
Rolling Mean on a Series with Null Values
When performing a rolling mean on a Polars Series with null values, Polars automatically skips the nulls within each window during the mean calculation. However, if all values in a window are null, the result is null.
import polars as pl
ser = pl.Series("numbers", [2, None, 6, None, 10])
# Rolling mean on a Series with null values
ser2 = ser.rolling_mean(window_size=3)
print("\nRolling mean with window size 3:\n", ser2)
# Output:
# Rolling mean with window size 3:
# shape: (5,)
# Series: 'numbers' [f64]
# [
# null
# null
# null
# null
# null
# ]
<a id="h-conclusion"></a>
Conclusion
In summary, Polars’ rolling_mean() method provides a powerful and flexible way to compute moving averages on Series data. Whether you need basic rolling means, centered windows, or weighted averages, it handles null values gracefully and works seamlessly with different data types.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Polars Series Shape Usage & Examples
- Polars Series sum() Method with Examples
- Polars Series describe() – Usage & Examples
- Polars Series shift() Function with Examples
- Polars Series min() – Explained by Examples
- Polars Series clear() – Explained by Examples
- Polars Series sample() Function with Examples
- Polars Series list.join() Function with Examples
- Polars Series explode() – Explained by Examples
- Polars Series struct.schema() – Explained by Examples
<a id="h-references"></a>
