AI Hints
Home›Data Science Tutorial›Pandas in Depth
Data Science · Lesson 6 of 101

Dates and Trends

Working with time.

⏱ 2 min read▶ Video at 10:46🎓 Free
Watch this lesson in the Data Science courseWatch on YouTube ↗Full Data Science course

A single number means little. Revenue of a million dollars. Is that good? Compared to what? The story is almost always in the change. Pandas has wonderful tools for dates, so let's use them.

Dates and Trends
From the video: Dates and Trends
  • One number means little
  • Compared to what?
  • The story is in the change

Weekdays and growth

When a column is a real date, the dt accessor gives you the weekday, the month, and more. We find the busiest weekdays, then sum revenue by month, and compare the last year with the first. Run it. Weekends are the strongest. And the business has grown over the year. The founder can use this for planning staff.

dates.pypython
import pandas as pd

sales = pd.read_csv("sales.csv", parse_dates=["date"])

sales["weekday"] = sales["date"].dt.day_name()
sales["month"] = sales["date"].dt.to_period("M")

print(sales.groupby("weekday")["revenue"].sum().sort_values().round(0).tail(3).to_string())
monthly = sales.groupby("month")["revenue"].sum()
print(monthly.tail(3).round(0).to_string())
print("Growth over the last year:", f"{monthly.iloc[-12:].sum() / monthly.iloc[:12].sum() - 1:.1%}")
Output
weekday
Wednesday     869304.0
Sunday       1067971.0
Saturday     1074394.0
month
2025-10    304887.0
2025-11    328751.0
2025-12    356262.0
Freq: M
Growth over the last year: 15.2%

Rolling averages

Daily numbers are noisy. A rolling average smooths them out. Rolling twenty eight averages the last four weeks, so whole weeks are included, which cancels the weekend effect. Percent change compares with a week ago. Run it. Now we can see the true level, and the direction. Always compare a weekday with the same weekday, or you'll just measure the weekend.

rolling.pypython
import pandas as pd

sales = pd.read_csv("sales.csv", parse_dates=["date"])
daily = sales.groupby("date")["revenue"].sum()

trend = daily.rolling(28).mean()
change = daily.pct_change(7)

print(daily.tail(2).round(0).to_string())
print("28 day average:", round(trend.iloc[-1]))
print("Change on last week:", f"{change.iloc[-1]:+.1%}")
print("Best day so far:", daily.idxmax().date(), round(daily.max()))
Output
date
2025-12-30    10620.0
2025-12-31    11017.0
28 day average: 11608
Change on last week: +2.0%
Best day so far: 2025-12-28 13883

Summary

Use real dates, smooth with rolling windows, and compare like with like. Our questions are now getting harder. To answer them, we need to combine tables.

Key takeaways
  • dt gives date parts
  • Rolling smooths noise
  • Compare like with like
Next up: Joining Tables — bringing data together