Advanced·15 min·datascience · pandas · timeseries
Time series with pandas
Time series: pandas' sweet spot
Once your DataFrame has a DatetimeIndex, a whole set of superpowers unlocks.
Building a DatetimeIndex
pd.date_range("2026-01-01", periods=365, freq="D")
pd.to_datetime(df["ts"])
df.set_index("ts", inplace=True)
Resampling — change the frequency
.resample("W")— weekly."W-SUN"= weeks ending Sunday..resample("MS")— month start."ME"— month end..resample("Q")/"Y"— quarterly / yearly.- Chain an aggregation:
.sum(),.mean(),.agg([...]), or.ohlc()(open/high/low/close — great for prices).
Downsample: coarser (daily → weekly). Upsample: finer (daily → hourly) — usually with .ffill() / .interpolate().
Rolling windows
s.rolling(7).mean() # 7-day moving average
s.rolling("7D").mean() # 7 calendar days (respects gaps)
s.rolling(30, min_periods=1).max() # 30-period max, no leading NaN
Shift, diff, pct_change
.shift(1)— lag by one period..diff()—s - s.shift(1), absolute change..pct_change()— percentage change (great for growth rates).
Timezones
.tz_localize("Asia/Kolkata")— attach a tz to naive timestamps..tz_convert("UTC")— convert between tzs.- Always store UTC in databases; convert on display.
Try it
- Compute a year-over-year growth rate on monthly data.
- Find the 7-day rolling max and label peaks where max == today.