…
…
Statistics and Data Analysis Fundamentals · Lesson 41 / 44 · Metrics and time
PreviewIn this lesson you will
resample (rates by summing numerator and denominator separately), and smooth the noise with a 7-day moving average to show the break date on a chartshift(7), pct_change) instead of with yesterday, so seasonality does not fool you, and explain why a match in timing is not proofYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The marketing table has, for every day from January to June, the ad spend, visitors, orders, and revenue. In lesson 40 you saw a drop in the monthly metrics starting in May, but the daily numbers go up and down so much that you cannot see on which day it started. In this lesson you will read the data as a time series, find the break date, and measure the change with a fair comparison.
At the end of this lesson you will be able to draw the chart below yourself. The thin line is the number of visitors each day. The thick line is the 7-day moving average of the same data. The dashed vertical line is May 1. The title says in one sentence what the chart shows: a line chart for time and a title that states the result, as you learned in lesson 17.
If you look at the thin line alone, you see a jagged saw: peaks on weekends, valleys on weekdays. The thick line smooths these teeth and leaves the real movement: a flat path around 1,550 until the end of April, a drop in the first week of May, and then a new flat path around 1,250. We will reach this chart in three steps: make the date the index and add up by period, smooth with a moving average, and compare while accounting for seasonality.
A time series is the values of the same variable measured at regular intervals: daily visitors, monthly revenue, hourly temperature. In most analyses so far, the order of the rows did not matter: if you shuffle the survey table, the average satisfaction does not change. In a time series, the order is the information. The observations are also not independent of each other: today's visitor count is similar to yesterday's, and this Saturday is similar to last Saturday. This is why, for a time series, you use tools that keep the order and understand dates.
Most of these tools want the date to be the index. In lesson 6 you used parse_dates to turn text dates into real dates. Now we take one more step: set_index("date") makes the date column the row label of the table. Now you can select rows by date instead of by position number. p.loc["2026-05"] selects all the days of May, and p.loc["2026-04-24":"2026-05-08"] selects the range between two dates (both ends included). Writing the month or the day is enough; pandas matches the text to the calendar.
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") cols = ["ad_spend", "visitors", "orders"] print(p.loc["2026-04-24":"2026-05-08", cols])
Output ad_spend visitors orders
date
2026-04-24 197.0 1377 5
2026-04-25 306.5 1935 2
2026-04-26 287.0 1781 4
2026-04-27 171.0 1464 4
2026-04-28 209.0 1460 3
2026-04-29 177.0 1279 10
2026-04-30 223.5 1513 13
2026-05-01 37.0 1354 1
2026-05-02 45.5 1502 5
2026-05-03 36.0 1340 6
2026-05-04 20.0 1120 1
2026-05-05 19.5 1155 5
2026-05-06 37.0 1214 2
2026-05-07 14.0 1213 3
2026-05-08 11.0 1102 4Even this two-week window says a lot. Ad spend was $223.50 on April 30 and $37.00 the next day: it fell to about one sixth overnight. Visitors do not fall that sharply: 1,377 on Friday, April 24, 1,354 on Friday, May 1, and 1,102 on Friday, May 8. Notice that we compared Friday with Friday; you will see why this matters in section 5. The orders column is almost unreadable on single days: 10, 13, 1, 5. Now choose for yourself.
Try it now· not graded; doesn't affect progress
Daily data is very detailed. To answer "How many orders did we get in May?", you need to add the days up into months. resample does exactly this: it looks at the date index, splits the rows into periods, and then calculates the summary you give for each period. Think of tearing the daily pages out of a calendar and putting them into weekly or monthly envelopes, and writing the total of the contents on the front of each envelope. It is similar to groupby from lesson 7, but the calendar decides the groups, not you. "MS" means monthly, labeled by the month start. "W" means weekly periods that end on Sunday.
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") monthly = p.resample("MS")["orders"].sum() print(monthly) print((monthly.pct_change() * 100).round(1).tolist())
Outputdate
2026-01-01 154
2026-02-01 177
2026-03-01 176
2026-04-01 162
2026-05-01 112
2026-06-01 104
Freq: MS, Name: orders, dtype: int64
[nan, 14.9, -0.6, -8.0, -30.9, -7.1]In the second line, pct_change() gives the change of each value compared with the one before it, as a ratio; multiplied by 100, it becomes a percent. From April to May, orders fell from 162 to 112: (112 − 162) / 162 = −30.9%. For January there is no previous month, so the result is nan. The monthly table shows the drop clearly, but it does not say which day it started. For that, we need a finer tool.
Before we move to weekly totals, here is a trap. January 1, 2026 is a Thursday, and the data ends on Tuesday, June 30. Because weeks close on Sunday, the first "week" contains only four days (Thursday to Sunday), and the last "week" contains only two days (Monday and Tuesday).
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") weekly = p.resample("W")["orders"].agg(["sum", "size"]) print(len(weekly)) print(weekly.head(2)) print(weekly.tail(2))
Output27
sum size
date
2026-01-04 19 4
2026-01-11 37 7
sum size
date
2026-06-28 23 7
2026-07-05 5 2size counts how many days are in each envelope. The first week has 19 orders, but in 4 days. The last week has 5 orders, in 2 days. These are not weeks with low orders; they are incomplete periods. On a chart, next to the other weeks, they look like fake drops at the start and at the end of the series. The same is true for the first month of data that starts in the middle of a month. The fix is simple: check the length of each period, and either leave the incomplete periods out of the comparison or convert them to a per-day average.
You drew Bazaar's weekly order totals as a bar chart. The first and last bars are clearly shorter than the others. What is the most likely reason?
The second trap in adding up is about the type of the measure. Orders and revenue are additive measures: a week's orders are the sum of the days' orders. The conversion rate (orders / visitors) is not like that. In lesson 13 you saw the trap of averaging rates: a day with few visitors gets the same weight as a day with many visitors. Adding up rates makes no sense at all: if you add seven daily rates of 0.3%, you get an invented number like 2.1%. The right way is to add up the numerator and the denominator separately first, and then divide.
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") monthly = p.resample("MS")[["orders", "visitors"]].sum() monthly["conversion"] = (monthly["orders"] / monthly["visitors"] * 100).round(2) print(monthly)
Output orders visitors conversion
date
2026-01-01 154 47863 0.32
2026-02-01 177 44089 0.40
2026-03-01 176 47850 0.37
2026-04-01 162 46593 0.35
2026-05-01 112 39233 0.29
2026-06-01 104 37864 0.27The monthly conversion rate is 0.32% in January and 0.27% in June. If you had taken the monthly average of the daily rates, you would get 0.36 for April and 0.28 for May: a small but needless error. The same rule applies to the average basket: the monthly revenue total divided by the monthly order total.
Match each measure with the correct way to calculate its monthly value from daily data.
For each row, pick its match from the list, then check.
The monthly total showed the drop but blurred its timing; the daily data shows the timing but drowns in noise. We need a tool between the two. A moving average is, for each day, the average of the last k days including that day. In pandas you write p["visitors"].rolling(7).mean(): rolling(7) puts a seven-day window on top of each row, and mean() takes the average of the seven values in the window. Then the window slides by one day and the calculation repeats.
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") avg7 = p["visitors"].rolling(7).mean() print(avg7.head(8).round(1))
Outputdate
2026-01-01 NaN
2026-01-02 NaN
2026-01-03 NaN
2026-01-04 NaN
2026-01-05 NaN
2026-01-06 NaN
2026-01-07 1565.4
2026-01-08 1556.1
Name: visitors, dtype: float64The first six days are empty (NaN): looking back from January 6, there are only six days, so the window is not full. The first value comes on January 7 and is the average of January 1–7. The value for January 8 is the average of January 2–8: the window slid by one day, January 1 left, and January 8 came in.
Why exactly 7? At Bazaar, the days of the week are very different from each other (weekends are high). Every seven-day window contains exactly one of each day: one Monday, one Tuesday, ..., one Sunday. So the weekday effect is balanced in the same way in every window, and what remains is the part that changes from week to week.
Let's look at this cost closely. On May 1 the level of visitors changed, but the moving average does not show it all at once:
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") avg7 = p["visitors"].rolling(7).mean() for day in ["2026-04-30", "2026-05-07", "2026-05-14"]: print(day, round(avg7[day]))
Output2026-04-30 1544
2026-05-07 1271
2026-05-14 1219The window on April 30 is entirely at the old level: 1,544. On May 7 the window is May 1–7, entirely at the new level: 1,271. On the days in between, part of the window is in April and part is in May; the average falls a little more each day. So in a moving average, the change does not appear on a single day. It spreads over a time as long as the window. Thinking that a moving average shows a change instantly is a common misunderstanding. If you make the window bigger, the noise is smoothed more, but the delay also gets longer. Try it yourself:
Change the window: how close is the moving average on May 7 to the new level (1,264 a day)?
Pick a value; predict the output first, then look.
1import pandas as pd2window = 73# Daily visitors from April 10 to May 7 (Bazaar, 28 days)4visitors = [1610, 1896, 1906, 1428, 1449, 1502, 1395, 1556, 1749, 1812,5 1396, 1486, 1277, 1373, 1377, 1935, 1781, 1464, 1460, 1279,6 1513, 1354, 1502, 1340, 1120, 1155, 1214, 1213]7v = pd.Series(visitors, index=pd.date_range("2026-04-10", periods=28))8avg = v.rolling(window).mean()9print("Window:", window, "days")10print("First full day:", avg.first_valid_index().date())11print("May 7 average:", round(avg["2026-05-07"]))12print("Distance to the new level (1,264):", round(avg["2026-05-07"] - 1264))
Window: 7 days First full day: 2026-04-16 May 7 average: 1271 Distance to the new level (1,264): 7
Faded lines didn't run with this value. The 3-day window on May 7 is even below the new level (1,194): it sees only the last three days and reflects the random lows of those days as they are. The 7-day window covers exactly one week, so it is very close to the new level (1,271). The 28-day window still carries three weeks of April (1,484): it has no noise but it is late; its first value can only appear on May 7.
Now try the same tool on another column. The cell below prints the monthly order totals and the 7-day visitor average on two dates.
Try it now· not graded; doesn't affect progress
A pattern that repeats at regular intervals is called seasonality. The name comes from the seasons of the year (ice cream in summer, winter jackets in winter), but the cycle can have any length: hours of the day, days of the week, months of the year. At Bazaar there is a strong weekly cycle. With dayofweek from lesson 6, let's find which day of the week each day is (0 = Monday, 6 = Sunday), and take the average with groupby from lesson 7. Because the date is the index, we write p.index.dayofweek.
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") day = p.groupby(p.index.dayofweek)["visitors"].mean().round(0) print(day)
Outputdate
0 1375.0
1 1353.0
2 1368.0
3 1368.0
4 1394.0
5 1694.0
6 1635.0
Name: visitors, dtype: float64Weekdays are between 1,353 and 1,394; Saturday is 1,694 and Sunday is 1,635. Weekends have about 300 more visitors. This information matters a lot when you compare. If you compare a Monday with the day before it, Sunday, you see an average "drop" of 260 visitors even if nothing has changed. Thinking that comparing with yesterday is always fair is the second big misunderstanding in this lesson.
A fair comparison is made with the same point of the cycle: Monday with last Monday, December with last year's December. In pandas, the tool for this is shift(k): it moves the series down by k rows, so the value from k days earlier comes next to each row. z - z.shift(7) compares each day with the same day a week earlier. If you want it as a percent, you use z.pct_change(7); the pct_change() in section 3 is really pct_change(1), a comparison with the previous row.
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") z = p["visitors"] diff_yesterday = z - z.shift(1) diff_week = z - z.shift(7) print("May 7:", z["2026-05-07"], "| yesterday:", z["2026-05-06"]) print("Last Thursday (April 30):", z["2026-04-30"]) print("Versus yesterday:", diff_yesterday["2026-05-07"]) print("Versus last week:", diff_week["2026-05-07"])
OutputMay 7: 1213 | yesterday: 1214
Last Thursday (April 30): 1513
Versus yesterday: -1.0
Versus last week: -300.0May 7 is a Thursday. Compared with yesterday, the difference is 1 visitor, and it is easy to say "no change". But May 6 was also a day at the new level, so the two days you compared are from the same low period. Compared with last Thursday (April 30), the difference is −300. Let's follow step by step how shift(7) works, with a small list. Here we use a plain list and a loop instead of pandas; the logic is the same: day i is paired with day i − 7.
Run the code line by line: see which line runs next, the variable boxes and the output.
days = ["Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu"] visitors = [1460, 1279, 1513, 1354, 1502, 1340, 1120, 1155, 1214, 1213] for i in range(len(visitors)): if i < 7: print(days[i], visitors[i], "-> no day 7 days earlier") else: previous = visitors[i - 7] diff = visitors[i] - previous print(days[i], visitors[i], "-> last", days[i - 7], previous, diff)
The list runs from Tuesday, April 28 to Thursday, May 7. For the first seven days there is nothing to compare with; in pandas, shift(7) writes NaN for these days. The eighth day (Tuesday, May 5) is compared with Tuesday, April 28: 1,155 − 1,460 = −305.
At Bazaar, 1,700 visitors came on a Sunday and 1,380 came the next Monday. Is this a drop?
Let's go back to the chart. On May 1, the series shows not a slowly sliding slope but a step: visitors go from one level to another and stay there. This is called a level shift, or a break. If you take the average before and after the break date, you get the height of the step: before May 1, an average of 1,553 visitors a day, and after, 1,264. That is a drop of about 18.6%.
For orders, the same break is hard to see in the daily data. The daily orders from April 27 to May 3 are 4, 3, 10, 13, 1, 5, 6: the jump to 10 and 13 orders on April 29 and 30, next to the 1 order on May 1, exaggerates or hides the break. In weekly totals the picture is cleaner: in the weeks of April, between 28 and 42 orders (average 36), and in the full weeks after May 4, between 20 and 28 orders (average 25). The week ending May 3 (42) mixes the two periods, so it belongs to neither.
To show the break on a chart, you use ax.axvline(date) in matplotlib: it draws a vertical line from top to bottom at the given x value. The code of the chart at the start of the lesson is six lines. Put the lines in the right order:
Put the lines of the code that draws the break chart from the start of the lesson in the right order (the import lines are ready).
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now the most important question: what happened on May 1? We know from the table: ad spend was $223.50 on April 30 and $37.00 on May 1. The campaign had ended. It is very tempting to say "visitors fell when the ads ended". But on the same day, Bazaar also launched the new checkout page. Two events fall on the same day, and a time series cannot separate the two. Linking the drop in visitors more to the ads is reasonable (a new checkout page does not change how many people come to the site, but whether those who come buy), but this is reasoning, not evidence.
A break date matching an event is a strong clue; as in lesson 37, changing together does not prove that one caused the other. Something else may have changed on the same day (a competitor's campaign, a public holiday, an update in the tracking code). In lesson 43 you will see a way to make this kind of comparison stronger, difference in differences; and the A/B test in lesson 42 separates the cause with an experiment.
The weekly cycle is not only in online stores; it is everywhere human behavior is measured. Let's look at the daily number of passengers on a city's public transit (in thousands, fictional sample data): on weekdays people go to work and school, and on weekends there are fewer trips; one week in between is a holiday week.
import pandas as pd # Daily public transit passengers (thousands): 3 weeks + 1 day, starting on Monday riders = pd.Series([452, 448, 455, 450, 468, 352, 296, # week 1 310, 285, 240, 205, 198, 215, 230, # week 2: holiday 456, 450, 449, 452, 470, 355, 300, # week 3 420]) # the 4th Monday print("Weekly total:", [int(riders[i:i + 7].sum()) for i in (0, 7, 14)]) today = riders.iloc[-1] print(f"Versus yesterday (Sunday): {round((today / riders.iloc[-2] - 1) * 100, 1)}%") print(f"Versus last Monday: {round((today / riders.iloc[-8] - 1) * 100, 1)}%")
OutputWeekly total: [2921, 1683, 2932]
Versus yesterday (Sunday): 40.0%
Versus last Monday: -7.9%The holiday week is a clear valley in the weekly total (2,921 → 1,683 → 2,932): this is not like the May 1 step at Bazaar; the level returns to its old place a week later. The last Monday can tell two different stories. Compared with yesterday's Sunday, it is a 40% increase; compared with last Monday, it is a drop of about 8%. Because Sunday is low every week, the first number says nothing; the second may point to a drop that is really worth attention.
A city spokesperson will make a statement on Monday evening. The draft has this sentence: "Yesterday we carried 300 thousand passengers, today 420 thousand: our services are preferred 40% more." The data team is asked for an opinion. What do you suggest?
Pick an option and see what happens. There are no points; you can try the other options too.
In this lesson you read a time series with three tools: the date index and resampling add up the periods (except rates), the moving average smooths the noise and shows the break, and comparing with the same point of the cycle removes seasonality. At Bazaar you now know the day the drop started: May 1. But a time series answers only "when"; for "why", you need to separate two things that changed on the same day. The strongest way to do this is an experiment: in lesson 42 you will analyze the data of the April A/B test from start to finish.
The average basket is a rate: its monthly value is found by dividing the revenue total by the order total.
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") monthly = p.resample("MS")[["orders", "revenue"]].sum() monthly["avg_basket"] = (monthly["revenue"] / monthly["orders"]).round(2) print(monthly)
Output orders revenue avg_basket
date
2026-01-01 154 9447.67 61.35
2026-02-01 177 13522.17 76.40
2026-03-01 176 11906.89 67.65
2026-04-01 162 10725.08 66.20
2026-05-01 112 8051.19 71.89
2026-06-01 104 5772.96 55.51In May the number of orders fell, but the average basket ($71.89) is higher than April's ($66.20); in June it fell to $55.51. You can see how much of the revenue drop comes from the number of orders and how much from the basket only by following the two measures separately.
Selecting by date range and putting the daily averages of the two periods side by side gives the size of the break for each column:
import pandas as pd p = pd.read_csv("marketing.csv", parse_dates=["date"]).set_index("date") cols = [, , ] before = p.loc[:, cols].mean() after = p.loc[:, cols].mean() (pd.DataFrame({: before, : after}).(1))
Calculating a weekly or monthly conversion rate by adding up or averaging the daily rates. Rates cannot be added; their averages also give too much weight to days with few visitors. First add up orders and visitors separately (resample("MS")[["orders", "visitors"]].sum()), and calculate the rate last. The second common mistake: comparing a day with yesterday and taking the weekend cycle for a "drop" or an "increase"; in a series with a weekly cycle, use shift(7) and look at the same day last week.
set_index("date")) makes selection with loc["2026-05"] and period totals with resample("W") / resample("MS") possible; watch for incomplete periods at the ends of the series, and calculate rates by adding up the numerator and denominator separately.rolling(7).mean() smooths the noise and the weekday effect; the cost is delay, and a change appears spread over a time as long as the window.shift(7), pct_change(7)); a break date matching an event is a clue, not proof.Next lesson: we will analyze the data of the April A/B test from start to finish.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output before after
ad_spend 224.5 24.5
visitors 1553.3 1263.9
orders 5.6 3.5Ad spend fell to one ninth, visitors fell by about 19%, and daily orders fell by about 36%. Orders falling more than visitors shows that the conversion rate also went down; part of this may be related to the new checkout page, but this table cannot separate that.