3. Connecting Data Sources (CSV, Excel, APIs & SQL)
Time-Series Dates, Rolling Averages & Period Comparisons
Analyze metrics over time accurately: parse DatetimeIndex values, aggregate daily logs into weekly/monthly buckets with resample(), smooth noise with rolling(), and compute growth with shift().
- Convert date strings to proper datetime indexes for chronological analysis
- Roll up daily events into weekly or monthly totals using resample()
- Smooth noisy metrics with moving averages (rolling) and compute period-over-period growth
Time-series questions sit at the heart of weekly business reviews: "What is our 7-day moving average of active learners? Did November revenue actually grow compared to October, or was November just a 5-weekend month? Why did signups dip last Tuesday?"
Plain string dates ("2026-11-05") cannot fill missing calendar days, align months, or compute rolling windows. Converting timestamps into real datetime64 indexes unlocks Pandas' chronological toolkit.
1. Parsing, Sorting & Indexing Timestamps
Always parse strings into datetime64 and sort chronologically before doing any window math (rolling, shift, pct_change):
import pandas as pd
df["ordered_at"] = pd.to_datetime(df["ordered_at"], errors="coerce")
df = df.dropna(subset=["ordered_at"]).sort_values("ordered_at")
df = df.set_index("ordered_at")
# Now slice whole months cleanly by string label!
november_orders = df.loc["2026-11-01":"2026-11-30"]If logs mix UTC timestamps (2026-11-28T23:30:00Z) with local timestamps, pass utc=True to pd.to_datetime(..., utc=True) and convert to your business reporting zone via .dt.tz_convert("America/Toronto") before grouping by calendar day—otherwise late-evening orders spill into tomorrow's UTC bucket!
2. resample() vs rolling(): Know the Difference
Raw Rows (Missing Tue!)
Mon(100) → Wed(120) → Thu(90)
After resample('D').sum()
Mon(100) → Tue(0) → Wed(120) → Thu(90)
Raw transaction logs skip quiet days with $0 sales; resampling to daily frequency restores missing calendar dates so a 7-day average actually spans 7 days.
Analysts often confuse .resample() and .rolling() because both operate across time. Use this mental model:
| Method | What It Does | Output Row Count | Typical Use Case |
|---|---|---|---|
.resample("W") / .resample("ME") | Buckets timestamps into non-overlapping calendar bins | Shrinks rows (e.g., 365 days → 52 weeks or 12 months) | Weekly/monthly revenue totals, filling quiet days ("D") |
.rolling(window=7) | Slides a moving window one row at a time | Same row count as input | 7-day moving average to smooth weekday/weekend spikes |
# 1. Bucket raw order events into continuous daily revenue (filling $0 days!)
daily = df["amount"].resample("D").sum().to_frame(name="revenue")
# 2. Bucket daily revenue into calendar weeks & months
weekly = daily["revenue"].resample("W").sum()
monthly = daily["revenue"].resample("ME").sum().to_frame(name="revenue")The Missing-Calendar-Days Trap
Suppose your boutique store had $0 sales on Tuesday. In your raw orders table, Tuesday has zero rows—it simply doesn't exist!
If you call raw_orders["amount"].rolling(window=7).mean() directly on raw transaction rows, Pandas averages the last 7 orders (or 7 active days)—NOT the last 7 calendar days! Always run .resample("D").sum() (or .asfreq(0)) first so quiet $0 days exist as explicit 0.0 rows in the timeline.
3. Smoothing Noise & Period-over-Period Growth
Daily product traffic almost always shows a strong 7-day seasonality (busy Mondays–Thursdays, quiet weekends). A 7-day rolling mean flattens that sawtooth pattern so leadership sees the underlying growth trend:
daily["ma_7d"] = daily["revenue"].rolling(window=7, min_periods=1).mean()
daily["mtd_revenue"] = daily.groupby(daily.index.to_period("M"))["revenue"].cumsum()
# Period-over-period comparisons on monthly totals
monthly["prev_month"] = monthly["revenue"].shift(1)
monthly["mom_diff"] = monthly["revenue"] - monthly["prev_month"]
monthly["mom_growth_pct"] = monthly["revenue"].pct_change() * 100Line-by-Line Walkthrough of min_periods=1 & shift(1)
rolling(window=7, min_periods=1).mean(): By default,rolling(7)returnsNaNfor the first 6 days until 7 observations exist. Settingmin_periods=1computes partial averages on Days 1–6 instead of leaving a blank gap at the start of your chart.monthly["revenue"].shift(1): Moves every row's value down by 1 period, placing October's revenue directly beside November's row so subtraction and% changebecome simple column math.monthly["revenue"].pct_change() * 100: Computes(current - prev) / prev * 100cleanly, returningNaNon the very first month where no prior period exists.
Try It Yourself in the Playground
Fill missing calendar days, compute a 3-day rolling average, and calculate day-over-day percentage change on daily learner signups in pure Python:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why should you sort your DataFrame by timestamp (df.sort_values("date")) before calling .rolling(7) or .shift(1)?
Quick Checkpoints
What does daily_sales.resample('ME').sum() do when daily_sales has a DatetimeIndex?
Which Pandas method shifts values down by 1 period so you can compare today vs yesterday (or this month vs last month)?
Why can calling .rolling(window=7).mean() directly on raw transaction rows produce misleading trends?