Time series with pandas
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.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Build a pandas Series named 'series' whose index is a DatetimeIndex of 7 daily dates starting 2026-01-01, with values [10, 20, 30, 40, 50, 60, 70]. Print the series.
- Exercise 2
You are given a daily series 'daily' of 21 days starting 2026-01-01 with values 1..21. Resample it to weekly sums ending on Sunday (W-SUN) and store as 'weekly'. Print 'weekly'.
- Exercise 3
Given a daily series 's' of values [1..10] indexed by 2026-01-01..2026-01-10, compute a 3-day rolling mean and store the value at positional index 5 (0-based), rounded to 2 decimals, in a variable named 'val5'. Print val5.