pandas/integer-lag-on-datetime-index
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| pandas | warning | none, edit by hand | All versions |
Integer .shift(n), .rolling(n), .diff(n), .pct_change(n), and row-counted .ewm(...) on a DatetimeIndex or datetime-sorted frame count rows rather than calendar time. Whenever timestamps have gaps (missing hours, weekends, holidays, or dropped sensor ticks), a 1-row lag silently reaches across the gap and a 7-row window spans more than 7 periods. Regularize onto a complete calendar grid with .asfreq(...) or .resample(...) first, or use calendar-aware freq=, a time-offset rolling window, or .ewm(halflife=..., times=...).
ts = df.set_index("day").sort_index()lag = ts["sold"].shift(1)avg = ts["sold"].rolling(7).mean()smooth = ts["sold"].ewm(span=7).mean()ts = df.set_index("day").sort_index().asfreq("D")lag = ts["sold"].shift(1)avg = ts["sold"].rolling("7D").mean()smooth = ts["sold"].ewm(halflife="2D", times=ts.index).mean()What the rule reports
Section titled “What the rule reports”The rule reports .shift(n), .rolling(n), .diff(n), .pct_change(n), and .ewm(...) without times= in a scope that shows unregularized calendar-time ordering (DatetimeIndex, .tz_localize / .tz_convert, parse_dates= with index_col=, .set_index(...) on a time column, or .sort_values(...) on a datetime column) without .asfreq(...), .resample(...), or .reindex(...):
.shift()or.shift(n)withoutfreq=,.rolling(n)with an integer window instead of a time offset string,.diff()/.diff(n)or.pct_change()/.pct_change(n)withoutfreq=, and.ewm(...)withouttimes=.
How to fix it
Section titled “How to fix it”- Regularize the index onto the expected calendar cadence before computing lags or windows:
ts = df.set_index("timestamp").sort_index().asfreq("h")or.resample("D").sum(). - Or keep the irregular index and pass explicit calendar arguments:
.shift(1, freq="h"),.rolling("24h").mean(),.pct_change(freq="D"), or.ewm(halflife="24h", times=ts.index).mean(). - For panel data with multiple series, regularize each series on its own calendar grid before grouped lags (or use
mlforecast/utilsforecastgap-filling helpers).
Diagnostic message
Section titled “Diagnostic message”Integer .shift() on a time-ordered frame counts rows, not calendar time, so missing timestamps silently shift across gaps. Reindex to a complete calendar grid with .asfreq(...) or .resample(...) first, or pass freq= (for example .shift(1, freq="h")).See all rules in the pandas pack.