…
…
Statistics and Data Analysis Fundamentals · Lesson 40 / 44 · Metrics and time
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Every month the management asks the same question: "How many orders did we get?" The number of orders fell in May, but it does not tell us why: at which step do visitors give up, did the carts get smaller, or do customers not come back? In this lesson you will split the drop into parts with three business metrics: the funnel, the revenue breakdown, and the cohort.
Unit 8 starts with this lesson. The tools you have learned so far (grouping, pivot tables, joins, ratios) now do a new job: building the few numbers a business looks at every month, and reading them correctly. There is no new pandas tool here; the tools of lessons 6–9 are enough.
By the end of the lesson you will produce the three small tables below from the Bazaar data yourself, and you will be able to explain each one in a sentence.
| Funnel (1,000 sessions) | Sessions | Added to cart | Checkout page | Purchased |
|---|---|---|---|---|
| Count | 1,000 | 335 | 195 | 105 |
| Step conversion | 33.5% | 58.2% | 53.8% |
| Month | Orders | Revenue ($) | Average order value ($) |
|---|---|---|---|
| April | 162 | 11,809 | 72.90 |
| May | 112 | 8,664 | 77.35 |
| June | 104 | 6,044 | 58.12 |
| Month | April | May | June |
|---|---|---|---|
| New customers (diagonal) | 95 | 48 | 29 |
| Returning customers | 53 | 57 | 70 |
Three sentences:
1. "Two out of three visitors leave without adding anything to the cart, and almost half of the people who reach the checkout page leave without buying."
2. "The revenue drop in May comes from the number of orders falling (from 162 to 112), not from smaller carts; in June, smaller carts were added to this."
3. "The return of old customers stayed about the same; what fell is the number of new customers (95, 48, 29)."
In a business, statistics is often used around a few key numbers called KPIs (key performance indicators). The monthly number of orders, revenue, and the number of active customers are such numbers. A good KPI has three properties: it has a clear definition, it is calculated the same way every month, and it is tied to a decision. In lesson 1 you saw the "question → metric" step, and in lesson 10 you wrote the definition of a metric; a KPI is a metric that is calculated again every month.
In this lesson we look at three families of metrics. Each one splits the sentence "orders fell" from a different side: the funnel shows the visitor's path, the revenue breakdown shows the size of the order, and the cohort table shows how the customer behaves over time.
Why do we need it? When you say "orders fell", you cannot know what to fix unless you know where visitors give up on the way to buying. Maybe people do not like the products (they do not add to the cart), or maybe the checkout page is confusing (they reach it but do not buy). The two problems need very different fixes.
A conversion funnel is the number of people who reach each step on the way to buying. At Bazaar the steps are: visiting the site (session), adding to the cart, going to the checkout page, and buying. At each step some visitors leave, so the numbers get smaller from top to bottom, and when you draw them they look like a funnel.
The Bazaar funnel data is in the file sessions.csv. Let's write one limit first: these 1,000 sessions are the sessions that took part in the checkout page test in April; they are not all the visitors of the site. Each row is a session; the columns added_to_cart, reached_checkout, and purchased show with 1 or 0 whether the session reached that step. The sum of a 1/0 column is the number of sessions that reached that step.
Two kinds of rates are calculated. The overall conversion is the number of people who reached a step divided by the number at the first step (the number of sessions). The step conversion is the number of people who reached a step divided by the number who reached the previous step. The denominators are different:
import pandas as pd s = pd.read_csv("sessions.csv") funnel = s[["added_to_cart", "reached_checkout", "purchased"]].sum() sessions = len(s) print("Sessions:", sessions) print(funnel) print("Overall conversion:", (funnel / sessions).round(3).tolist()) print("Cart / session:", round(funnel["added_to_cart"] / sessions, 3)) print("Checkout / cart:", round(funnel["reached_checkout"] / funnel["added_to_cart"], 3)) print("Purchase / checkout:", round(funnel["purchased"] / funnel["reached_checkout"], 3))
OutputSessions: 1000
added_to_cart 335
reached_checkout 195
purchased 105
dtype: int64
Overall conversion: [0.335, 0.195, 0.105]
Cart / session: 0.335
Checkout / cart: 0.582
Purchase / checkout: 0.538Of the 1,000 sessions, 335 added to the cart, 195 went to the checkout page, and 105 bought. The overall conversion is 33.5%, 19.5%, and 10.5%. The step conversions are 33.5% (session to cart), 58.2% (cart to checkout), and 53.8% (checkout to purchase). The two rates of the first step are the same, because the "previous step" of the first step is the session itself.
Run the code yourself. Then add a filter under the second line and look at the funnel of only first-time visitors:
Try it now· not graded; doesn't affect progress
In the 427 sessions of new visitors, the overall conversion is 31.9%, 18.5%, and 8.9%: a little lower than all sessions at every step. Someone who sees the site for the first time buys a little less than someone who has come before; this is expected.
There is a common mistake when reading a funnel: "The step with the lowest rate is the biggest problem." If you look at the overall conversion, the lowest rate is always at the last step (10.5%), because the overall conversion is always divided by the same denominator (1,000 sessions), and the numbers get smaller as you go down. This does not say that the last step is bad; it only says that the last step is at the bottom. To compare the steps with each other, we look at the step conversion: of the people who arrived at a step, how many did it pass to the next one?
Of 1,000 sessions, 195 reached the checkout page and 105 bought. What share of the people who reached the checkout page leave without buying?
The calculation of step conversion is just three divisions: each number is divided by the one before it. Follow it line by line below; rate is calculated with a new denominator in each round:
Run the code line by line: see which line runs next, the variable boxes and the output.
steps = [1000, 335, 195, 105] names = ["cart", "checkout", "purchase"] for i in range(1, 4): rate = steps[i] / steps[i - 1] lost = steps[i - 1] - steps[i] print(names[i - 1], round(rate, 3), "lost:", lost)
The three step conversions are 33.5%, 58.2%, and 53.8%. The numbers of people lost are 665, 140, and 90. By far the biggest loss is between the session and the cart: 66.5% of visitors leave without adding any product to the cart. But do not ignore the checkout step either: a person who reaches the checkout page has chosen a product, filled the cart, and is almost a buyer. Losing 46% of these people is expensive; a small fix here turns directly into sales. Which step to invest in first depends both on the step conversion and on the value of the person lost at that step.
There is one more good thing about the funnel: it can be split into groups. These 1,000 sessions were actually an experiment; half saw the old checkout page (A) and half saw the new page (B). Let's put the funnels of the two groups side by side with the groupby from lesson 7:
import pandas as pd s = pd.read_csv("sessions.csv") t = s.groupby("group")[["added_to_cart", "reached_checkout", "purchased"]].sum() t["sessions"] = s.groupby("group").size() t["cart"] = (t["added_to_cart"] / t["sessions"]).round(3) t["checkout"] = (t["reached_checkout"] / t["added_to_cart"]).round(3) t["purchase"] = (t["purchased"] / t["reached_checkout"]).round(3) print(t[["sessions", "cart", "checkout", "purchase"]])
Output sessions cart checkout purchase
group
A 500 0.31 0.619 0.677
B 500 0.36 0.550 0.404In the first two steps the groups are close, but in the move from checkout to purchase, A has 67.7% and B has 40.4%. The new checkout page seems to lose people exactly at the step that was changed. You can test whether this difference is by chance with the two-proportion test in lesson 31; in lesson 42 we will open this experiment as a full A/B test. Remember a warning from lesson 31 too: a step conversion is also a proportion, and when it is calculated on a small denominator, its uncertainty is large. B has 99 people at the checkout step; with this number, a difference of a few percentage points can come from chance.
Why do we need it? When the management says "revenue fell", two very different things may have happened: either fewer people placed orders, or the people who ordered spent less. In the first case you look at winning customers; in the second case you look at the product and price mix. The total number does not separate the two.
A metric decomposition splits a total metric into its factors and finds which factor the change comes from. The factors of revenue are simple: revenue = number of orders × average order value. The average order value (AOV) is revenue divided by the number of orders.
Let's build the monthly table in one step with dt.month from lesson 6 and the named agg from lesson 7:
import pandas as pd o = pd.read_csv("orders.csv") o["date"] = pd.to_datetime(o["date"]) o["month"] = o["date"].dt.month k = o.groupby("month").agg( orders=("order_id", "count"), revenue=("amount", "sum"), customers=("customer_id", "nunique"), ) k["aov"] = (k["revenue"] / k["orders"]).round(2) k["revenue"] = k["revenue"].round(2) print(k)
Output orders revenue customers aov
month
1 154 11395.34 127 74.00
2 177 15674.15 144 88.55
3 176 13257.35 160 75.33
4 162 11809.05 148 72.90
5 112 8663.60 105 77.35
6 104 6044.08 99 58.12From April to May, revenue went down from $11,809 to $8,664. Which factor went down? The number of orders fell from 162 to 112; the average order value rose from $72.90 to $77.35. So the sentence "if revenue fell, customers must be spending less" is wrong for May: spending per order went up, and the number of orders went down. In June the picture changes: orders fall to 104 and the AOV also gets smaller, to $58.12. The shrinking in June comes largely from fewer expensive Electronics orders (29 Electronics orders in April, 15 in June).
The customers column is the number of different customers in each month (nunique); this is called monthly active customers. May has 105 active customers. This number includes both people who came for the first time and people who had come before; we will separate them in section 6.
A note on definitions: this revenue includes all orders, including returned and canceled ones. For net revenue you first need to filter with status == "completed". Try it yourself:
Try it now· not graded; doesn't affect progress
With completed orders only, April has 145 orders and an AOV of $73.97, and May has 98 orders and an AOV of $82.16. The numbers changed with the definition, but the story stayed the same: the number of orders fell in May. This is why the definition of a metric is part of the report.
To see the change as a percentage, let's use the after / before - 1 calculation from lesson 10. Change the month below and read the change in orders, AOV, and revenue compared with April:
Change the month: does the drop compared with April come from the number of orders or from the average order value?
Pick a value; predict the output first, then look.
1month = 52orders = {4: 162, 5: 112, 6: 104}3revenue = {4: 11809.05, 5: 8663.60, 6: 6044.08}4aov_april = revenue[4] / orders[4]5aov = revenue[month] / orders[month]6print("Month:", month)7print(f"Orders change (%): {(orders[month] / orders[4] - 1) * 100:.1f}")8print(f"AOV change (%): {(aov / aov_april - 1) * 100:.1f}")9print(f"Revenue change (%): {(revenue[month] / revenue[4] - 1) * 100:.1f}")
Month: 5 Orders change (%): -30.9 AOV change (%): 6.1 Revenue change (%): -26.6
Faded lines didn't run with this value. In May, orders fell 30.9% and the AOV rose 6.1%: the revenue drop (26.6%) comes entirely from the number of orders. In June, orders fell 35.8% and the AOV fell 20.3%: the two factors together cut revenue almost in half (48.8%). When you choose April, all changes are 0; a month compared with itself does not change.
Why do we need it? May has 105 active customers and April has 148. Who dropped? Are they new customers who are discovering Bazaar for the first time, or customers who had shopped before and no longer come back? The number of monthly active customers does not separate the two; both are inside the same number.
A cohort table divides customers into groups (cohorts) by the month of their first purchase and follows how many people from each group come back in later months. The rows are cohorts (the month of the first purchase), and the columns are calendar months.
We build the table in four steps. (1) Get the month of each order. (2) Find the first order month of each customer: group by customer and take the smallest month; this is the customer's cohort. (3) Add this cohort information to the orders with the merge from lesson 9. (4) With the pivot_table from lesson 8, count the different customers in the cohort × month table:
import pandas as pd o = pd.read_csv("orders.csv") o["date"] = pd.to_datetime(o["date"]) o["month"] = o["date"].dt.month first = o.groupby("customer_id", as_index=False).agg(cohort=("month", "min")) print(first.head(3)) o = o.merge(first, on="customer_id", how="left") t = o.pivot_table(index="cohort", columns="month", values="customer_id", aggfunc="nunique", fill_value=0) print(t)
Output customer_id cohort
0 M0001 2
1 M0008 6
2 M0009 3
month 1 2 3 4 5 6
cohort
1 127 36 30 26 17 19
2 0 108 13 12 16 13
3 0 0 117 15 16 12
4 0 0 0 95 8 18
5 0 0 0 0 48 8
6 0 0 0 0 0 29First look at the first table: M0001 placed the first order in month 2, and M0008 in month 6. The merge carries this information to all orders of the customer. aggfunc="nunique" counts a customer once even if they placed two orders in one month; what is counted here is people, not orders.
Now read the table. The diagonal (from top left to bottom right) is the new customers of each month: because the cohort of a customer is the month of their first purchase, the cell where the cohort and the purchase month are the same counts the first purchase. The diagonal is 127, 108, 117, 95, 48, 29: the number of new customers halved in May and fell below a third in June. The cells to the right of the diagonal are the returns: from the January cohort, 36 people came back in February and 30 in March. The returns of the old cohorts are between 8 and 36 people a month, about 8–28% of the cohort size, and there is no clear collapse in May–June. The zeros below the diagonal are cohort-month combinations that do not exist yet: someone who comes for the first time in March cannot have shopped in January.
The sum of a column is the active customers of that month: the May column is 17 + 16 + 16 + 8 + 48 = 105. Of the same 105 people, 48 are new and 57 are old. In April, 95 of the 148 people were new. So almost all of the drop in active customers is in winning new customers. In May the ads had been stopped (lesson 10); if we think that ads bring mostly new customers, the table fits this. We will open the relation between ads and time in lesson 41.
Put the four lines of the code in the right order:
Put the four lines that build the cohort table in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Match each part of the table with its meaning:
Match each part of the cohort table with its meaning.
For each row, pick its match from the list, then check.
The cohort table gives detail month by month; sometimes you want a single summary number. The repeat purchase rate is the number of customers who placed at least two orders divided by all customers who placed an order:
import pandas as pd o = pd.read_csv("orders.csv") count = o.groupby("customer_id")["order_id"].count() print("Customers who ordered:", len(count)) print("At least two orders:", (count >= 2).sum()) print("Repeat purchase rate:", round((count >= 2).mean(), 3))
OutputCustomers who ordered: 524
At least two orders: 217
Repeat purchase rate: 0.414Of the 524 customers who ordered in six months, 217 bought at least twice: 41.4%. This number also has a definition: is it within a six-month window, or over a lifetime? Our number sees only these six months. This is the other end of the window warning in the cohort table:
The data ends in June. If you calculate the repeat purchase rate of only the 29 customers who shopped for the first time in June, how will it compare with the rate of the January customers?
A funnel is used not only in e-commerce but in every process that moves step by step. In a fictional language learning app, the records of one month are these: 10,000 people downloaded the app, 6,200 opened an account, 3,100 finished their first lesson, and 900 opened the app again on the seventh day.
steps = {"download": 10000, "account": 6200, "first_lesson": 3100, "day7": 900}
names = list(steps)
for i in range(1, len(names)):
previous, current = names[i - 1], names[i]
step = steps[current] / steps[previous]
overall = steps[current] / steps["download"]
lost = steps[previous] - steps[current]
print(f"{previous} -> {current}: step {step:.2f}, overall {overall:.2f}, lost {lost}")Outputdownload -> account: step 0.62, overall 0.62, lost 3800
account -> first_lesson: step 0.50, overall 0.31, lost 3100
first_lesson -> day7: step 0.29, overall 0.09, lost 2200The step conversions are 62%, 50%, and 29%. The lowest step conversion is at the last step: only 29% of the people who finished the first lesson come back a week later. The most people, however, are lost at the first step (3,800). Which step should get the investment? Think about this question with a suggestion you might hear in a team meeting:
The product team of the app brings a suggestion: "Let's increase the ad budget and double the number of downloads (to 20,000); more downloads means more users." What do you recommend?
Pick an option and see what happens. There are no points; you can try the other options too.
Let's go back to the management's sentence "orders fell". The funnel showed that two thirds of visitors leave without adding any product to the cart, and that almost half of those who reach the checkout page leave without buying; the new checkout page (B) looks bad at exactly this step. The revenue breakdown showed that the drop in May came not from smaller carts but from the number of orders. The cohort table showed that the return of old customers stayed about the same, and that the drop was in winning new customers. None of these three sentences proves a cause on its own; each one tells you where to look. We will examine the drop in group B of the funnel with an A/B test in lesson 42, and the drop in new customers with time and ad data in lesson 41.
In June the average order value fell to $58.12. Let's look at the category mix:
import pandas as pd o = pd.read_csv("orders.csv") o["date"] = pd.to_datetime(o["date"]) o["month"] = o["date"].dt.month last3 = o[o["month"] >= 4] t = last3.pivot_table(index="month", columns="category", values="amount", aggfunc="count", fill_value=0) print(t) el = o[o["category"] == "Electronics"].groupby("month")["amount"].agg(["count", "mean"]).round(2) print(el.loc[4:6])
Outputcategory Beauty Books Clothing Electronics Home & Living
month
4 29 23 46 29 35
5 18 17 26 22 29
6 15 15 32 15 27
count mean
month
4 29 123.32
5 22 130.26
6 15 97.77Electronics orders went from 29 in April to 15 in June, and the mean amount of the Electronics orders in June also fell from $123.32 to $97.77. The most expensive category both shrank and got cheaper; this is why the AOV fell. The AOV is also a weighted mean (lesson 13): when the category mix changes, it moves even if the price of no product changed.
Taking the average of monthly rates as the rate of the period. The conversion rate of a period is total orders / total visitors; it is not the plain mean of the daily rates. In a plain mean, the rate of a busy day and the rate of a quiet day get the same weight, but the busy day has many more visitors. This is the "mean of rates" trap from lesson 13:
import pandas as pd day = pd.DataFrame({"visitors": [100, 100, 2000], "orders": [5, 5, 20]}) day["rate"] = day["orders"] / day["visitors"] * 100 print("Mean of daily rates (%):", round(day["rate"].mean(), 2)) print("Total / total (%):", round(day["orders"].sum() / day["visitors"].sum() * 100, 2))
OutputMean of daily rates (%): 3.67
Total / total (%): 1.36In three days, 2,200 visitors placed 30 orders: the rate of the period is 1.36%. The mean of the daily rates says 3.67%, because the high rates (5%) of the two quiet days with 100 visitors got the same weight as the busy day with 2,000 visitors. First add up, then divide.
Next lesson: we will treat daily data as a time series and see the day when the ads were stopped with moving averages and period comparisons.
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.
When we make the definition of the metric "completed orders":
import pandas as pd o = pd.read_csv("orders.csv") o["date"] = pd.to_datetime(o["date"]) o["month"] = o["date"].dt.month done = o[o["status"] == "completed"] k = done.groupby("month").agg(orders=("order_id", "count"), revenue=("amount", "sum")) k["aov"] = (k["revenue"] / k["orders"]).round(2) k["revenue"] = k["revenue"].round(2) print(k)
Output orders revenue aov
month
1 137 9447.67 68.96
2 155 13522.17 87.24
3 155 11906.89 76.82
4 145 10725.08 73.97
5 98 8051.19 82.16
6 97 5772.96 59.52The numbers are different from those calculated with all orders, but the story from April to May is the same: orders fall from 145 to 98, and the AOV rises from $73.97 to $82.16. In your report, write which definition you used, and use the same one every month.