Data analysis with pandas · Lesson 13 of 15

Dates and time series

Build a series of dates, use dates as the index, pick days and months, total sales by week or month with resample and smooth with rolling.

About 16 minutes · code runs in your browser, nothing to install

A time series is a list of values measured over time: daily sales, hourly temperatures, monthly bills. pandas works best with them when the dates are real dates and sit in the index.

Making dates

pd.date_range(start, periods=n, freq="D") makes n dates in a row. freq can be "D" for days, "W" for weeks (ending on Sunday) or "MS" for the start of each month. Here a café's sales for two weeks get a date each.

Pythoneditable
import pandas as pd

days = pd.date_range("2026-03-02", periods=14, freq="D")
sales = [120, 135, 128, 150, 210, 260, 90,
         125, 140, 132, 158, 220, 275, 95]
s = pd.Series(sales, index=days)

print(s.head(7))
print("From", s.index[0].date(), "to", s.index[-1].date())
Output
2026-03-02    120
2026-03-03    135
2026-03-04    128
2026-03-05    150
2026-03-06    210
2026-03-07    260
2026-03-08     90
Freq: D, dtype: int64
From 2026-03-02 to 2026-03-15

2 March 2026 is a Monday, so the first week runs Monday to Sunday.

Picking dates

With dates in the index you can select by a date string, or slice a range of dates; both ends are included. The .day_name() of the index gives weekday names, handy for grouping.

Pythoneditable
import pandas as pd

days = pd.date_range("2026-03-02", periods=14, freq="D")
sales = [120, 135, 128, 150, 210, 260, 90,
         125, 140, 132, 158, 220, 275, 95]
s = pd.Series(sales, index=days)

print(s["2026-03-07"])
print(s["2026-03-06":"2026-03-08"])
by_day = s.groupby(s.index.day_name()).mean()
print(by_day[["Friday", "Saturday", "Sunday"]])
Output
260
2026-03-06    210
2026-03-07    260
2026-03-08     90
Freq: D, dtype: int64
Friday      215.0
Saturday    267.5
Sunday       92.5
dtype: float64

Resampling: weekly and monthly totals

resample is groupby for time: it puts the values into time buckets and summarises each. resample("W").sum() gives weekly totals, labelled with the Sunday that ends each week. "MS" makes monthly buckets labelled with the first of the month.

Pythoneditable
import pandas as pd

days = pd.date_range("2026-03-02", periods=14, freq="D")
sales = [120, 135, 128, 150, 210, 260, 90,
         125, 140, 132, 158, 220, 275, 95]
s = pd.Series(sales, index=days)

print(s.resample("W").sum())
print(s.resample("W").mean().round(1))
Output
2026-03-08    1093
2026-03-15    1145
Freq: W-SUN, dtype: int64
2026-03-08    156.1
2026-03-15    163.6
Freq: W-SUN, dtype: float64
Pythoneditable
import pandas as pd

bills = pd.DataFrame({
    "day": pd.to_datetime(["2026-01-05", "2026-01-20", "2026-02-03",
                           "2026-02-17", "2026-03-02"]),
    "amount": [45.0, 30.5, 52.0, 18.0, 40.0],
})
monthly = bills.set_index("day").resample("MS")["amount"].sum()
print(monthly)
Output
day
2026-01-01    75.5
2026-02-01    70.0
2026-03-01    40.0
Freq: MS, Name: amount, dtype: float64

With a DataFrame, set the date column as the index first, then resample.

Rolling averages and changes

rolling(3).mean() gives the average of each value and the 2 before it, which smooths out ups and downs. The first two values have no full window, so they are NaN. diff() gives the change from the day before.

Pythoneditable
import pandas as pd

days = pd.date_range("2026-03-02", periods=14, freq="D")
sales = [120, 135, 128, 150, 210, 260, 90,
         125, 140, 132, 158, 220, 275, 95]
s = pd.Series(sales, index=days)

week1 = s.head(7)
out = pd.DataFrame({
    "sales": week1,
    "avg3": week1.rolling(3).mean().round(1),
    "change": week1.diff(),
})
print(out)
Output
            sales   avg3  change
2026-03-02    120    NaN     NaN
2026-03-03    135    NaN    15.0
2026-03-04    128  127.7    -7.0
2026-03-05    150  137.7    22.0
2026-03-06    210  162.7    60.0
2026-03-07    260  206.7    50.0
2026-03-08     90  186.7  -170.0

Drawing the series

Pythoneditable
import pandas as pd

days = pd.date_range("2026-03-02", periods=14, freq="D")
sales = [120, 135, 128, 150, 210, 260, 90,
         125, 140, 132, 158, 220, 275, 95]
s = pd.Series(sales, index=days)
import matplotlib.pyplot as plt

print("Best day:", s.idxmax().date(), "with", s.max(), "€")
s.plot(marker="o", title="Daily sales (€)")
s.rolling(7).mean().plot(label="7-day average")
plt.legend(["daily", "7-day average"])
plt.tight_layout()
plt.show()
Output
Best day: 2026-03-14 with 275 €
Chart drawn by this code

A time series draws naturally as a line chart, with the dates along the bottom.

✎ Exercise

Total the café sales by week with resample, then print the date of the best week and its total.

Hint: weekly = s.resample("W").sum(); idxmax() gives the label of the largest value.

Your codewrite your answer, then Run
import pandas as pd

days = pd.date_range("2026-03-02", periods=14, freq="D")
sales = [120, 135, 128, 150, 210, 260, 90,
         125, 140, 132, 158, 220, 275, 95]
s = pd.Series(sales, index=days)

# your code here

Expected output:

2026-03-08    1093
2026-03-15    1145
Freq: W-SUN, dtype: int64
Best week ends 2026-03-15 with 1145
Show a solution
Solutioneditable
import pandas as pd

days = pd.date_range("2026-03-02", periods=14, freq="D")
sales = [120, 135, 128, 150, 210, 260, 90,
         125, 140, 132, 158, 220, 275, 95]
s = pd.Series(sales, index=days)

weekly = s.resample("W").sum()
print(weekly)
print("Best week ends", weekly.idxmax().date(), "with", weekly.max())
Output
2026-03-08    1093
2026-03-15    1145
Freq: W-SUN, dtype: int64
Best week ends 2026-03-15 with 1145

Check yourself

1. What does s.resample("W").sum() give?

2. Why are the first two values of rolling(3).mean() NaN?

3. Which freq makes buckets labelled with the first day of each month?

Spotted a mistake on this page? Tell us