…
…
Statistics and Data Analysis Fundamentals · Lesson 13 / 44 · Distribution and center
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.
The marketing team put a category summary table in the monthly report, took the mean of the five category means, and wrote "average order value at Bazaar is $71.6". In the previous lesson you calculated the mean from all orders, and it was $75.5. In this lesson you will find where the difference comes from and learn to rebuild the correct overall mean from a summary table.
By the end of this lesson you will be able to read the table below and say which of the two numbers under it is correct, and why:
Output count mean
category
Beauty 138 27.9
Books 117 21.8
Clothing 266 68.5
Electronics 156 146.5
Home & Living 208 93.1
Plain mean: 71.6
Weighted: 75.5Both numbers come from the same five rows. One is exactly the same as the mean of all orders. The other is not the mean of any set of orders. The difference is in how much say each row gets.
In this lesson you will:
In lesson 12 you saw the definition of the mean: total divided by count. This definition has a quiet consequence: if you multiply the mean by the count, you get the total back. If a branch got 100 orders and its average order value is $50, then the branch revenue is 100 × $50 = $5,000. This reverse calculation is what saves you when you have no raw data, only a summary table.
Now think about a small situation. A store has two branches. Branch A got 100 orders this month, with an average order value of $50. Branch B got only 10 orders, but its average order value is $100. The manager asks: "What is the overall average order value of the two branches?" Make a guess before you calculate.
Branch A: 100 orders, mean $50. Branch B: 10 orders, mean $100. What is the mean order value of all orders in both branches, in dollars?
The answer 75 feels very natural: there are two numbers, so you take the middle. But the question is not "the mean of the two branches". It is "the mean of all orders in the two branches". Imagine you put all the orders in one bag: there are 100 orders around $50 and 10 orders around $100. If you pull one order from the bag at random, it will most likely be one of A's orders. For the mean to be 75, the two branches would need to give the same number of orders.
Example 1 (small numbers): Two branches
a_orders, a_mean = 100, 50 b_orders, b_mean = 10, 100 plain = (a_mean + b_mean) / 2 total_revenue = a_orders * a_mean + b_orders * b_mean overall = total_revenue / (a_orders + b_orders) print("Plain mean:", plain) print("Total revenue:", total_revenue) print("Overall mean:", round(overall, 1))
OutputPlain mean: 75.0
Total revenue: 6000
Overall mean: 54.5The calculation has three steps: multiply each branch mean by its own number of orders (this gets the total revenue back), add the products, and divide by the total number of orders. These three steps are called the weighted mean. The general formula is written like this: Σ(value × weight) / Σ(weight). The Σ sign means "add them all up". The value is the branch mean; the weight is how many orders that mean represents. The denominator is the sum of the weights, not the number of groups: we divide by 110, not by 2.
NumPy does this calculation with one function: np.average(values, weights=weights). If you do not give weights, np.average takes the plain mean; so np.average(x) and x.mean() give the same result. The real difference is in the weights argument, and the most common mistake is to forget it.
In the code below, branch A is fixed (100 orders, $50) and B's mean is $100. Change the number of orders for B and watch the two lines.
Change the number of orders for branch B: how do the plain mean and the weighted mean behave?
Pick a value; predict the output first, then look.
1import numpy as np23means = [50, 100]4b_orders = 105counts = [100, b_orders]6print("Plain:", sum(means) / 2)7print("Weighted:", round(np.average(means, weights=counts), 1))
Plain: 75.0 Weighted: 54.5
Faded lines didn't run with this value. The plain mean never sees the number of orders; it stays at 75 all the time. The weighted mean moves toward the crowded branch: when B is small it is close to A's $50, and when B is crowded it is close to $100. When the two branches have the same size (100 and 100), the two results are the same. The weighted mean is not always larger, or always smaller, than the plain mean; its direction depends on which group is crowded.
This small experiment clears up three misunderstandings at once. First, the plain mean does not see the group size; the crowded group and the small group each get "one vote". Second, the weighted mean is not always smaller or always larger than the plain mean: with 10 orders for B it is 54.5 (smaller than the plain mean), and with 500 orders it is 91.7 (larger). Third, if the groups have the same size, the two ways give the same result; the problem appears when the sizes are unequal. The result always stays between the two group means, and it is close to the crowded group.
Now let's go back to the case. The marketing team had a category summary made with the pattern from lesson 7: for each category, the number of orders (count) and the mean amount (mean). The team took the mean of the mean column. This is the same as the 75 in the two-branch calculation: it counts the five categories as equal.
Example 2 (case): Overall mean from category means
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") g = orders.groupby("category")["amount"].agg(["count", "mean"]) print(g.round(1)) print("Plain mean:", round(g["mean"].mean(), 1)) print("Weighted:", round(np.average(g["mean"], weights=g["count"]), 1)) print("From raw data:", round(orders["amount"].mean(), 1))
Output count mean
category
Beauty 138 27.9
Books 117 21.8
Clothing 266 68.5
Electronics 156 146.5
Home & Living 208 93.1
Plain mean: 71.6
Weighted: 75.5
From raw data: 75.5The mean weighted with the order counts is exactly the same as the mean calculated from the raw data: $75.5. This is not a coincidence. Each category mean × its number of orders gives the revenue of that category; adding the five revenues and dividing by 885 is the same job as dividing the total of all orders by 885.
Why is the plain mean smaller? The two cheapest categories, Books ($21.8) and Beauty ($27.9), are also the two categories with the fewest orders: 117 and 138. Only 29% of all orders come from these two, but in the plain mean they got two votes out of five, which is 40% of the say. Cheap categories with few orders were counted too much, so the result was pulled down. The direction is important: the plain mean moves down if the means of the small groups are lower than those of the large groups, and up if they are higher. Try it yourself:
Try it now· not graded; doesn't affect progress
In the first try, the plain mean is now larger than the real mean (76.9). When you split by device, the group with fewer orders is desktop (369 orders), and its average order value is higher than mobile's ($84.9 against $68.8). When the small group is expensive, the plain mean moves up. The weighted mean stays at 75.5 whichever column you group by: the same 885 orders, the same total.
Until now the weight was always "how many orders". But the weight changes with what the question counts. The manager has a new question: "At what price do we sell our products on average?" In the orders table, each row has a unit_price and a quantity. If 3 pieces of the same product were bought in one order, then 3 products were sold at that price. In the question "average price of the products sold", a row with three pieces sold must count three times as much as a row with one piece.
Example 3 (case): Average selling price
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") print(round(orders["unit_price"].mean(), 1)) print(round(np.average(orders["unit_price"], weights=orders["quantity"]), 1)) print(round((orders["unit_price"] * orders["quantity"]).sum() / orders["quantity"].sum(), 1)) print(orders.groupby("quantity")["unit_price"].agg(["count", "mean"]).round(1))
Output56.3
54.4
54.4
count mean
quantity
1 621 58.5
2 181 53.5
3 52 46.6
4 31 46.2The plain mean is $56.3, and the mean weighted by quantity is $54.4. The third line does the same calculation with the formula: the sum of price × quantity is divided by the sum of the quantities. The result is the same as with np.average. The last table shows the reason for the difference: in orders with one piece the average price is $58.5, and in orders with four pieces it is $46.2. Customers buy many pieces of cheap products; counting the pieces pulls the mean toward the cheap products. Which one is "correct"? It depends on the question. The answer to "What is the average unit price in one order?" is 56.3; the answer to "What is the average price of the products we sold?" is 54.4. First find what the question counts; that is the weight. Match the questions below with the right weight.
Match each question with the weight you need for the correct answer.
For each row, pick its match from the list, then check.
In lesson 7 you saw that a rate is really a mean: the mean of a True/False column is the share of True values. So the same trap exists in rates. Averaging the return rates of two groups and calling it the "overall return rate" is the same mistake as averaging two branch means. The correct overall rate is the total number of returns divided by the total number of orders; this is also equal to the mean of the group rates weighted by the number of orders.
Example 4 (case): Return rate by device
import pandas as pd orders = pd.read_csv("orders.csv") orders["returned"] = orders["status"] == "returned" t = orders.groupby("device").agg(orders=("order_id", "count"), returned=("returned", "sum")) t["rate"] = t["returned"] / t["orders"] * 100 print(t.round(2)) print("Plain mean (%):", round(t["rate"].mean(), 2)) print("Overall rate (%):", round(t["returned"].sum() / t["orders"].sum() * 100, 2))
Output orders returned rate
device
desktop 369 23 6.23
mobile 516 41 7.95
Plain mean (%): 7.09
Overall rate (%): 7.2364 of the 885 orders were returned: 7.23%. The plain mean of the two device rates is 7.09%. The difference is small, because the two groups are close in size (369 and 516) and the rates are also close. But the principle is the same: the overall rate is between 6.23% and 7.95%, closer to the crowded mobile group. When the sizes and the rates differ more, as across categories, the difference grows; you will see this in the Examples section.
If you have only a summary table, how do you build the overall mean row by row? Put the lines below in the right order. The table g is the table with count and mean columns from Example 2.
Put the lines in order to calculate the overall average order value from the category summary table.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
You may have seen a weighted mean for the first time without noticing, on a report card or a transcript. At a university each course has a number of credits, and the semester grade average is weighted with the credits. Say a student has three courses: Mathematics with 6 credits and a grade of 50, Physical Education with 1 credit and a grade of 100, and History with 3 credits and a grade of 70.
Example 5 (outside the case): Credit-weighted grade average
import numpy as np grades = [50, 100, 70] credits = [6, 1, 3] print("Plain mean:", round(sum(grades) / len(grades), 1)) print("Credit-weighted mean:", round(np.average(grades, weights=credits), 1))
OutputPlain mean: 73.3
Credit-weighted mean: 61.0The plain mean is 73.3; the credit-weighted mean is 61. The difference of 12 points comes from the 100 in the 1-credit Physical Education getting as much say in the plain mean as the 50 in the 6-credit Mathematics. The student spends 6 hours of the week on Mathematics; the mean should reflect this. Change the credits and watch how the result moves.
Try it now· not graded; doesn't affect progress
In the second try, the credit-weighted mean is the same as the plain mean: if the weights are equal, the weighted mean is the plain mean. In the third try, the credit-weighted mean changes more, because Mathematics has the largest weight.
The practical rule is simple. If you have raw data (a table where each order is one row), calculate the overall mean directly from the raw data: orders["amount"].mean(). There is no need to go around through a summary table, and there is no chance to make a mistake. If you have only a summary (a report from another team, a news article, a presentation), weight each mean with its own count. If the summary table has no count column, the overall mean cannot be found from that table.
There is also a more striking form of the trap in this lesson: in a comparison, one side is ahead in every group, but the other side is ahead in the total. You will see this in lesson 37; the idea in this lesson is at its base: the sizes of the groups decide the total result. We are done with the measures of the center. But two groups with the same mean can be very different: in one, everyone is close to the mean, and in the other, the values are spread out. Next is measuring this spread.
The difference was small across devices. Across categories, the group sizes and the rates differ more, so the plain mean is clearly off.
import pandas as pd orders = pd.read_csv("orders.csv") orders["returned"] = orders["status"] == "returned" k = orders.groupby("category").agg(orders=("order_id", "count"), returned=("returned", "sum")) k["rate"] = k["returned"] / k["orders"] * 100 print(k.round(2)) print("Plain mean (%):", round(k["rate"].mean(), 2)) print("Overall rate (%):", round(k["returned"].sum() / k["orders"].sum() * 100, 2))
Output orders returned rate
category
Beauty 138 5 3.62
Books 117 2 1.71
Clothing 266 45 16.92
Electronics 156 5 3.21
Home & Living 208 7 3.37
Plain mean (%): 5.76
Overall rate (%): 7.23The plain mean is 5.76%, and the real rate is 7.23%. Clothing has the high return rate and it is the most crowded category; the plain mean gives it only one fifth of the say, so the rate is pulled down. The overall rate is again the same as in the device example: the same 885 orders, the same 64 returns.
Taking the mean of a summary table. When you have a summary table g, writing g["mean"].mean() is the shortest way, and the code gives no error at all:
overall = g["mean"].mean() # 71.6: each category is one vote, wrong overall = np.average(g["mean"], weights=g["count"]) # 75.5: correct
The first line counts the five categories as equal; the result is not the mean of any set of orders. The second line weights each mean with its own number of orders, and it gives the same result as orders["amount"].mean() calculated from the raw data. The same mistake also happens when you write np.average(x) and forget the weights argument: without weights, np.average is the plain mean. If you have raw data, take the overall mean from the raw data; if you have only the summary, weight with the counts.
np.average(means, weights=counts). The result is the same as the mean calculated from the raw data.Next lesson: Two groups can have the same mean, but in one the values are close to the mean and in the other they are spread out. Next is measuring the spread and the standard deviation.
Exercises and quiz are for members
This lesson has 5 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
A cinema has two halls: the big hall has 200 seats and is 90% full; the small hall has 50 seats and is 40% full. The cinema says "our average occupancy is 65%".
import numpy as np seats = [200, 50] occupancy = [0.90, 0.40] print("Plain:", round(sum(occupancy) / 2, 2)) print("Weighted by seats:", round(np.average(occupancy, weights=seats), 2)) print("Full seats:", round(200 * 0.90 + 50 * 0.40), "/", sum(seats))
OutputPlain: 0.65
Weighted by seats: 0.8
Full seats: 200 / 250200 of the 250 seats are full: the real occupancy is 80%. The "65%" comes from counting the empty seats of the small hall as important as those of the big hall.
If the groups are close in size, the plain mean also stays close to the truth.
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") orders["month"] = pd.to_datetime(orders["date"]).dt.month m = orders.groupby("month")["amount"].agg(["count", "mean"]) print(m.round(1)) print("Plain:", round(m["mean"].mean(), 1), "· Weighted:", round(np.average(m["mean"], weights=m["count"]), 1))
Output count mean
month
1 154 74.0
2 177 88.6
3 176 75.3
4 162 72.9
5 112 77.4
6 104 58.1
Plain: 74.4 · Weighted: 75.5The months have between 104 and 177 orders; the difference is $1.16. Across categories it was $3.97. The more unequal the groups, the more the plain mean is off; but a small difference is also not a reason to use the wrong number.