Skip to content

polars/polars-row-lag-on-time-series

Pack Severity Fix Versions
Polars warning none, edit by hand All versions

Row-counted .shift(n), .diff(n), .pct_change(n), and .rolling_mean(n) / .rolling_sum(n) expressions on a Polars time series count rows rather than elapsed calendar time. When timestamps have gaps, a 1-row shift reaches across missing periods and a 7-row rolling window stretches across more than 7 periods. Regularize onto a complete calendar grid with .upsample(time_column=..., every=...) first, or use time-based .rolling_*_by(by=..., window_size="...") or .group_by_dynamic(...).

out = df.sort("ts").with_columns(
lag=pl.col("y").shift(1),
avg=pl.col("y").rolling_mean(7),
)
out = df.sort("ts").upsample(time_column="ts", every="1d").with_columns(
lag=pl.col("y").shift(1),
avg=pl.col("y").rolling_mean_by("ts", window_size="7d"),
)

The rule reports row-counted .shift(n), .diff(n), .pct_change(n), and .rolling_(mean|sum|std|var|min|max|median|quantile|skew)(n) calls in a Polars scope that shows time-series evidence (datetime_range, date_range, pl.Datetime, pl.Date, .str.to_datetime / .str.to_date / .str.strptime, or .sort(...) on a time column) without .upsample(...), .group_by_dynamic(...), or .join_asof(...).

  • Regularize the time grid before row lags with df.sort("ts").upsample(time_column="ts", every="1d") (passing group_by=... for panel series).
  • Replace .rolling_mean(7) with .rolling_mean_by("ts", window_size="7d") (or .group_by_dynamic("ts", every="1d", period="7d")) to measure elapsed calendar time directly.
Row-counted .shift(), .diff(), or .pct_change() on a Polars time-series scope shifts across missing timestamps instead of calendar time. Regularize the grid with .upsample(time_column=..., every=...) first, or use .group_by_dynamic(...) / .join_asof(...).

See all rules in the Polars pack.