Trend smoothing
Smooth noisy numeric columns while retaining one output per input row.
Polars · Module
Computes a fixed-size moving mean over an expression or Series. It supports optional elementwise weights, a minimum non-null threshold, and centered output labels.
rolling_mean evaluates a fixed-size moving window over an expression or Series and aggregates each window to its mean. The current row and preceding window_size - 1 rows are included; optional weights, a minimum non-null count, and centered labels change how results are produced.
Expr.rolling_mean(window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False) → Expr| Name | Type | Description |
|---|---|---|
window_size | int | Length of the window in number of elements. |
weights | list[float] | None | Optional slice with the same length as the window, multiplied elementwise with window values; expression weights are normalized to sum to 1. |
min_samples | int | None | Number of non-null window values required before computing a result; defaults to window_size when None. |
center | bool | Whether to set labels at the center of the window. |
A Series for polars.Series.rolling_mean or an Expr for polars.Expr.rolling_mean.
window_size argument.min_samples specifies the non-null count needed before producing a result.min_samples=None, a result requires a complete window of non-null values.center=True changes result labeling by centering each window instead of using the trailing position.import polars as pl
df = pl.DataFrame({"value": [100, 200, 300, 400, 500]})
result = df.with_columns(
pl.col("value").rolling_mean(window_size=2).alias("mean_2")
)
print(result)Adds a two-element trailing rolling mean to the DataFrame.
Smooth noisy numeric columns while retaining one output per input row.
Calculate short-window averages in a DataFrame transformation.
Apply custom relative importance to values within each fixed window.
rolling_mean calculate?It computes a moving mean over a fixed-length window. At each row, the window contains that row and the preceding window_size - 1 elements.
Follow-up: How would you avoid early partial results? Set min_samples to window_size, which is also the default when it is None.
window_size is the number of elements in each window. weights optionally supplies one multiplier per window element, while min_samples controls how many non-null values are required.
Follow-up: What constraint applies to weights? The weights must have the same length as the window; expression weights are normalized to sum to one.
The method returns a Series when called on a Series and an Expr when called on an expression. The expression form can be used inside DataFrame transformations such as with_columns.
Follow-up: How can a window be aligned differently? Pass center=True to set labels at the center of the window.
polars.Series.rolling_meanpolars.Expr.rolling_mean_bypolars.Expr.rolling_sumpolars.Expr.rolling_minpolars.Expr.rolling_max