…
…
Statistics and Data Analysis Fundamentals · Lesson 3 / 44 · Asking questions with data
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 brought the manager of Bazaar two "findings": the average basket of the last 100 orders dropped to $59.30, so customers now spend less, and a survey shows that 71% of customers are satisfied. Both calculations are correct, but both answer the wrong question. In this lesson you will learn to write one question at the top of every analysis: whom does this data describe, and which claim can it support?
In lesson 1 we built the analysis cycle: question, data, cleaning, exploration, inference, decision. In lesson 2 we looked at the table and asked what one row describes. In this lesson we ask one more question in the "data" step of the cycle: where did these rows come from? There is no calculation error in the marketing team's two findings. The average was taken correctly and the percentage was divided correctly. The problem is not in the calculation but in the way the data was selected. However clean a table is, you cannot get a correct general statement from wrongly selected rows.
In this lesson you will:
First, let's be clear about whom we are talking about. The population is all the observations you want to talk about. The manager's question is about January to June, so the population is all of Bazaar's orders in these six months: 885 orders. A sample is the piece you actually have: observations selected from the population and examined.
If you already have the whole population, why bother with a sample? Most of the time you do not have it. You cannot send a survey to every customer, you cannot measure the sleep time of every student in a country, and you cannot burn every light bulb a factory makes until it fails. This is why a large part of statistics is about looking at a small piece and talking about the whole. Whether this is reliable depends on one thing: how the piece was selected.
The data-world version of stirring is a random sample: every member of the population has an equal chance of being selected. Think of a lottery drum: the numbers of the 885 orders go into the drum, it is mixed well, and 100 are drawn. No order is chosen because it is "close at hand" or "looks interesting".
First let's measure the population itself, because we will compare the samples with it. We write two small functions: the share of mobile orders (number of mobile orders divided by the number of rows) and the average amount (sum of amounts divided by the number of rows).
Example 1 (case): Measures of the population
import csv with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) def mobile_share(items): mobile = sum(1 for r in items if r["device"] == "mobile") return round(mobile / len(items) * 100, 1) def avg_amount(items): total = sum(float(r["amount"]) for r in items) return round(total / len(items), 1) print("Population:", len(rows), mobile_share(rows), avg_amount(rows))
OutputPopulation: 885 58.3 75.5In the population, 58.3% of orders came from mobile, and the average amount is $75.5. These two numbers will be the "correct answer" of this lesson: how close does a sample get to them, and if it does not get close, why?
The difference between population and sample depends on the question, not on the table. The same 885 orders are the population for the manager's January–June question. If we asked about "all customers of Bazaar across all years", they would be a sample.
Match each situation with population or sample, according to the question being asked.
For each row, pick its match from the list, then check.
Let's return to the marketing team's first finding. The "last 100 orders" is the easiest sample to take: the last 100 rows of the table. But the table is sorted by date, so all of these 100 orders come from June. This is called a convenience sample: observations that were not selected at random but taken because they were close at hand. To draw a random sample we use three steps you know from the Python course: copy the list, mix it with random.shuffle, and slice the first 100 items. random.seed(42) reproduces the same mix every time, so your result matches ours.
Example 2 (case): Last 100 orders and 100 random orders
import csv import random with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) def mobile_share(items): mobile = sum(1 for r in items if r["device"] == "mobile") return round(mobile / len(items) * 100, 1) def avg_amount(items): total = sum(float(r["amount"]) for r in items) return round(total / len(items), 1) last100 = rows[-100:] print("Last 100:", mobile_share(last100), avg_amount(last100), "| first date:", last100[0]["date"]) random.seed(42) shuffled = rows[:] random.shuffle(shuffled) sample = shuffled[:100] print("Random 100:", mobile_share(sample), avg_amount(sample))
OutputLast 100: 52.0 59.3 | first date: 2026-06-02
Random 100: 57.0 72.5The average of the last 100 orders is $59.3. This is the number the marketing team called "dropped to $59.30". The population's is $75.5. The random 100 orders give $72.5 and 57.0% mobile. Notice that the random sample did not match the population exactly either. This is normal: every draw of 100 orders gives a slightly different result. The difference is that a random sample falls a bit high in one draw and a bit low in another; it does not move systematically in one direction.
An analyst found the average amount of the 'last 100 orders' to be $59.3. The population average is $75.5. Why is there a difference?
The cell below is the code of Example 2. First run it as it is, then try the two experiments in the comment lines.
Try it now· not graded; doesn't affect progress
In the second experiment the first 100 orders (January) give $77.4, while the last 100 (June) give $59.3. A convenience sample describes whichever month it happens to fall on. What is wrong is not the number itself, but generalizing June's number to the whole period as "customers now spend less". Why June is low is a separate and interesting question, but to ask it you first need to know that this number describes only June.
If a selection method systematically gives some observations more or less chance, the result shifts in the same direction every time you repeat it. This is called bias. The error of a random method is scattered: sometimes up, sometimes down, around the target on average. The error of a biased method can be tight: the results are very similar to each other, but all of them are next to the target. The last 100 orders are the same 100 orders today and tomorrow; they give the same wrong number with confidence every time.
Bias has two common forms. You have seen the first: the convenience sample, observations that are close at hand (the latest orders, your nearest friends, people you meet at the school door). The second is the voluntary response: the person decides for themselves whether to enter the sample. Who answers a survey? Mostly people who are very satisfied or very angry; people in the middle do not bother. The result again shifts systematically in one direction.
Drawing a random sample correctly is a matter of order. First a copy is made so the original list is not damaged; then the copy is shuffled; then it is sliced.
Put the lines that print the mobile share of 100 random orders 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
Now let's look at the marketing team's second finding, the survey. Bazaar's survey.csv file has 300 answers, and every answer has an order_id column that shows which order it came from. We can look up these numbers in the orders table and check the status of the orders.
Example 3 (case): Who was the survey sent to?
import csv from collections import Counter with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) with open("survey.csv", encoding="utf-8") as f: survey = list(csv.DictReader(f)) status = {r["order_id"]: r["status"] for r in rows} survey_ids = [a["order_id"] for a in survey] print("In the survey:", Counter(status[i] for i in survey_ids)) print("In the orders:", Counter(r["status"] for r in rows))
OutputIn the survey: Counter({'completed': 300})
In the orders: Counter({'completed': 787, 'returned': 64, 'canceled': 34})All 300 people who answered the survey have a completed order. The survey was sent only to completed orders. The owners of the 64 returned and 34 canceled orders, 98 people in total and the ones expected to be the least satisfied, are in the population but not in the sample at all. This is why the sentence "71% are satisfied" cannot be said about "all our customers". The sentence that can be said is "71% of the customers whose orders were completed and who answered the survey are satisfied."
There is one more interesting detail: in the same survey the mobile share is 58.0% and the average delivery time is 2.97 days; in the orders these numbers are 58.3% and 2.98. On these two measures the survey looks very much like the population. Do not let this mislead you: being similar on one measure is not being similar on every measure. Delivery time may hardly affect the decision to return an order, but satisfaction is directly affected; the 98 people left outside are different exactly on the satisfaction question.
To see the effect of voluntary response yourself, let's build a small world. Example 4 (simulation, outside the case): 70% of a fictional population of 10,000 people are satisfied (population = ["satisfied"] * 7000 + ["not satisfied"] * 3000). 30% of the people who are not satisfied answer the survey. The percentage of satisfied people who answer is in the variable satisfied_reply. For every person a number between 1 and 100 is drawn; if the number is less than or equal to that person's percentage, the person answers. Change the value and look at how many people answered and what the survey says.
Change the percentage of satisfied people who answer the survey (satisfied_reply). People who are not satisfied answer at a 30% rate every time; the true share of satisfied people in the population is 70%.
Pick a value; predict the output first, then look.
1import random23satisfied_reply = 604random.seed(42)5population = ["satisfied"] * 7000 + ["not satisfied"] * 30006replies = []7for person in population:8 percent = satisfied_reply if person == "satisfied" else 309 if random.randint(1, 100) <= percent:10 replies.append(person)11share = replies.count("satisfied") / len(replies) * 10012print("Answered:", len(replies), "| satisfied share (%):", round(share, 1))
Answered: 5021 | satisfied share (%): 82.3
Faded lines didn't run with this value. The true share is 70%. When the two groups answer at the same rate (30%), the survey comes out close to the truth (69.4%). When satisfied people answer more often, the largest survey (5,021 people) is the most wrong one (82.3%): making the sample larger does not fix bias.
The true share is 70% every time. When the two groups answer at the same rate (30%), the survey is very close to the truth: 69.4%. When satisfied people answer more often, the survey says 82.3%, and it says so with 5,021 people. The largest survey is the most wrong one. A larger sample does not fix bias; it only makes the wrong answer look more confident.
So far we have asked "whom does it describe?". The second question is: can this data support a cause-and-effect claim? Bazaar's orders table is observational: you only record what happened. Nobody forced a customer to shop on mobile or on desktop; every customer chose for themselves. On May 1, mobile orders dropped. On the same date the new mobile checkout page went live, the ad campaign ended, and one category got a price increase (we talked about the manager's hypothesis in lesson 1). Observational data cannot separate these three changes: you cannot know which one caused the drop, or whether all three did together.
In an experiment, on the other hand, you form the groups: people are assigned to two groups by coin toss (at random), and only one group gets the new thing. Because of random assignment, the groups are similar on average in everything, such as age, device, and habits; only one difference remains, the change being tested. So if a difference in results appears between the groups, the cause is that change. Experiments also use extra safeguards such as a placebo or blinding; the first step is always random assignment. When you run experiments with people, not harming them and protecting their personal data are also part of the design.
Bazaar ran exactly this kind of experiment: in the second half of April, visitors were randomly split into group A (old checkout page) and group B (new checkout page); the records are in sessions.csv. We will open its result in lesson 42. For now, let's only look at how similar random assignment makes the groups.
Example 5 (case): The groups of the A/B experiment
import csv from collections import Counter with open("sessions.csv", encoding="utf-8") as f: sessions = list(csv.DictReader(f)) print(Counter(s["group"] for s in sessions)) print("New visitors:", Counter(s["group"] for s in sessions if s["new_visitor"] == "1"))
OutputCounter({'A': 500, 'B': 500})
New visitors: Counter({'B': 214, 'A': 213})The groups have 500 sessions each, and their numbers of new visitors are almost equal: 213 and 214. Nobody said "new arrivals go to B"; the coin toss balanced this by itself. For mobile and desktop customers in the orders table there is no such balance, because people formed those groups themselves.
Match each study with the claim it can support.
For each row, pick its match from the list, then check.
The whole idea of the lesson comes down to two questions. The first question is who was selected? If the observations were selected at random from the population, you can generalize the result to the population; if they were selected by convenience or by volunteering, the result describes only the sample. The second question is how were the groups formed? If the groups were assigned at random, you can make a cause-and-effect claim; if they formed by themselves, only a relationship.
| Groups assigned at random | Groups formed by themselves | |
|---|---|---|
| Selected from the population at random | Cause and effect, generalizes to the population (e.g., students drawn by lottery from a class list are split into two methods by lottery) | Relationship, generalizes to the population (e.g., 500 randomly selected people are asked about sleep and grades) |
| Not selected at random | Cause and effect, only for the participants (e.g., Bazaar's A/B experiment; volunteer students with a lottery) | Relationship, only for the sample (e.g., Bazaar's order records; a survey at a shop door) |
Example 6 (outside the case): Bike lane news. A city council announces: "There are fewer traffic accidents in neighborhoods with bike lanes." This data is observational: the council chose the neighborhoods where bike lanes would be built. Bike lanes were most likely built in newer neighborhoods with wide streets and already calm traffic. The low number of accidents can come from the bike lane or from the width of the streets. To show cause and effect, you would list similar neighborhoods, build lanes in some of them by lottery and not in the others, and compare accidents. In practice this cannot always be done, but knowing which design shows what lets you read the news correctly.
An app says '90% of our users recommend us.' The survey was shown inside the app to people who had been using it for 10 days. Which interpretation is the most correct?
Finally, try these questions in a real work conversation.
The manager writes: 'Mobile orders dropped after the new checkout page. The page lowered sales. Write it like this in your report.'
Pick an option and see what happens. There are no points; you can try the other options too.
If you want to apply everything you did in this unit to a news headline, the unit task (G1, question a news headline) is waiting for you as the recommended stop.
Does making a convenience sample bigger help? Let's look at the last 100, 200, and 300 orders.
import csv with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) def avg_amount(items): return round(sum(float(r["amount"]) for r in items) / len(items), 1) for n in [100, 200, 300]: last = rows[-n:] print("Last", n, "| first date:", last[0]["date"], "| average:", avg_amount(last)) print("Population average:", avg_amount(rows))
OutputLast 100 | first date: 2026-06-02 | average: 59.3
Last 200 | first date: 2026-05-05 | average: 68.1
Last 300 | first date: 2026-04-14 | average: 71.1
Population average: 75.5The average gets closer because as the slice grows, April's orders also come in; the slice grows toward the population itself. But all three results are below the population: a convenience sample always shifts in the same direction.
Let's repeat the random draw 20 times and count how many stay above the population average and how many below.
csv
random
(, encoding=) f:
rows = (csv.DictReader(f))
avg_amount(items):
(((r[]) r items) / (items), 1)
random.seed(42)
above = 0
below = 0
i (20):
shuffled = rows[:]
random.shuffle(shuffled)
avg_amount(shuffled[:100]) > 75.5:
above += 1
:
below += 1
(, above, , below)
(, avg_amount(rows[-100:]))"The sample is large, so the result is reliable." Bias does not disappear as the sample grows: in the voluntary response simulation, the survey of 5,021 people said 82.3%, and the true share was 70%. A large sample reduces the chance error of a random draw, but it carries the error of the selection method unchanged. The right way: first ask "how was it selected?", and only then "how many people?".
Next lesson: We read data together with where it came from; now we move to pandas to work with large tables, and everything you did in this unit will be a single line there.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output20 random draws: above 9 | below 11
Last 100 every time: 59.3The random draws fall on the two sides of the population about equally; this is the left target of the archer diagram. The last 100 gives the same wrong number every time; this is the right target.