…
…
Statistics and Data Analysis Fundamentals · Lesson 2 / 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.
To answer the manager's question "Sales went down, why?", the team shared seven Bazaar tables: orders, customers, products, sessions, survey, marketing, and a raw order dump. Before you calculate anything, you need to get to know the table you will use most, orders.csv. Your job today is to make a "variable card" for this table.
By the end of this lesson you will be able to write a card like the one below for orders.csv and the survey table. Each row has a column name, its type, the summary that fits that type, and the result in Bazaar's data:
| Column | Type | Fitting summary | In Bazaar |
|---|---|---|---|
device | categorical, nominal | count, share | mobile 516 (58.3%) |
quantity | numeric, discrete | total, mean, range | total 1,263, mean 1.43, 1–4 |
customer_id | categorical, nominal (an identifier, not a number) | number of distinct values | 524 customers |
satisfaction (survey) | categorical, ordinal | count, share (share of "4 or 5") | 71.3% |
In statistics, the first question is not "which calculation should I run?" but "what type of data do I have?" The type of a column decides which summary makes sense for it, and later which chart and which test. If you read the type wrong, the calculation is mathematically correct but tells you nothing. Python will calculate the mean of any column without complaining. You decide whether that mean means anything. This lesson teaches you how to make that decision.
When you look at a table, the first question to ask is: what does one row describe? The answer is called the unit of observation. In the orders table it is an order, in the customers table it is a customer, and in the sessions table it is one visit to the site. Here are some columns from the first three rows of orders.csv:
| order_id | date | customer_id | device | category | quantity | amount | status | carrier | delivery_days |
|---|---|---|---|---|---|---|---|---|---|
| S00001 | 2026-01-01 | M0116 | desktop | Home & Living | 2 | 249.9 | completed | Gull Post | 3 |
| S00002 | 2026-01-02 | M0113 | desktop | Electronics | 1 | 74.95 | completed | Caravan Freight | 4 |
| S00003 | 2026-01-02 | M0026 | desktop | Home & Living | 1 | 164.95 |
In a well-organized table, three rules hold: every row is one observation, every column is one variable, and every cell holds a single value. This layout is called a tidy table (*tidy data*). If a cell said "2 items, mobile", or if each month had its own column, you would have to fix the table before you could do the same calculation. Bazaar's tables follow this rule, and pandas, which you will use from lesson 4, expects this layout too.
The column that gives away the unit of observation is the key column: its value is different in every row. In the orders table this is order_id, because every order number appears once. customer_id can repeat, because the same customer can place several orders. This small difference has a big consequence: "how many orders are there?" and "how many customers are there?" are different questions, and the same table answers them with different numbers.
Let's read the file with csv.DictReader, which you learned in the Python course, and find the number of rows and the number of distinct customers. To count distinct values we use a set: a set keeps each value only once.
import csv with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) print(len(rows), len(set(r["customer_id"] for r in rows))) print(rows[0]["order_id"], rows[0]["customer_id"], rows[0]["amount"])
Output885 524
S00001 M0116 249.9The table has 885 rows but only 524 distinct customers. So a row is not a person. Predict:
What does one row of orders.csv show?
Now try the same code on other tables. The unit of observation changes from table to table. If the number of rows equals the number of distinct values in a key column, that column identifies the row on its own.
Try it now· not graded; doesn't affect progress
Once you have found the unit of observation, you move on to the columns. Variables are first split into two groups. A categorical (qualitative) variable names a group: device, category, carrier, order status. A numeric (quantitative) variable measures an amount: quantity, order amount, delivery days. To see why this split matters, think of it this way: you cannot add "mobile" and "desktop", but you can add 2 items and 3 items. Which operation makes sense depends on the type of the variable.
Each group is split once more. A categorical variable can be nominal: there is no order among the categories, and "mobile" and "desktop" are simply different. Or it can be ordinal: there is a meaningful order, but the gaps are not equal. In a satisfaction score, 5 is better than 4, but nobody can say that the difference between 4 and 5 equals the difference between 1 and 2. A numeric variable can be discrete: you get it by counting, and it has no values in between (quantity 1, 2, 3; there is no order of 2.5 items). Or it can be continuous: you get it by measuring, and in principle it can take any value between two values (amount, time, height).
To find the type of a column, you only need to ask three questions in order. Is the value a label or an amount? If it is a label, can the values be put in a meaningful order? If it is an amount, was it obtained by counting or by measuring? The answers give the type, and the type gives the summary. Put the steps in the right order:
Put the steps for finding the type of a column in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now apply these questions to Bazaar's columns. The recommend score (0–10) and the time spent on the checkout page also come from the survey and sessions tables.
Choose the type of each variable.
For each row, pick its match from the list, then check.
One note: for numeric variables, "twice as much" only makes sense when there is a true zero. A $2,000 order really is twice a $1,000 order, because $0 means "no money at all". But 20 °C is not twice as warm as 10 °C; 0 °C is not the absence of temperature, it is the point where water freezes. Statistics books call this the difference between the "interval" and "ratio" scales. In this course the main split is nominal, ordinal, discrete, and continuous.
We found the type; now comes the useful part. To describe a column at a glance, we make a summary, and each type has its own summary:
| Type | Fitting summary | Example in Bazaar |
|---|---|---|
| Nominal | Count and share; most common value | device: mobile 516 (58.3%) |
| Ordinal | Count table and share of the top groups; a mean only with a warning | satisfaction: 71.3% gave 4 or 5 |
| Discrete, continuous | Total, mean, smallest–largest | quantity: total 1,263, mean 1.43, 1–4 |
A share is the count of a value divided by the total count and multiplied by 100. To count each value in a nominal column, the Counter from the Python course is a perfect fit; most_common() sorts the counts from largest to smallest:
import csv from collections import Counter with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) counts = Counter(r["device"] for r in rows) for value, n in counts.most_common(): print(value, n, round(n / len(rows) * 100, 1))
Outputmobile 516 58.3
desktop 369 41.758.3 percent of the orders came from mobile. A share says more than a count: if you see the number 516 alone, you cannot tell whether it is big or small, but 58.3 percent shows right away that it is more than half of the total.
In a numeric column, the total, the mean, and the range are useful. The mean is the total divided by the number of values; the range is the region between the smallest and the largest value. Values that come from a CSV are strings, so we convert them with int() first:
import csv with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) quantity = [int(r["quantity"]) for r in rows] print("Total:", sum(quantity), "Mean:", round(sum(quantity) / len(quantity), 2), "Min:", min(quantity), "Max:", max(quantity))
OutputTotal: 1263 Mean: 1.43 Min: 1 Max: 4885 orders sold 1,263 items; an order has 1.43 items on average, and no order has more than 4 items. You cannot make the same summary for device: "mobile" has no mean. The other way around, you can count quantity, but the total and the mean give the real information.
An ordinal variable sits between the two. Let's count the satisfaction scores in the survey. This time we print the counts in score order, because in ordinal data the order is information:
import csv from collections import Counter with open("survey.csv", encoding="utf-8") as f: survey = list(csv.DictReader(f)) counts = Counter(int(a["satisfaction"]) for a in survey) for score in sorted(counts): print(score, counts[score]) top = counts[4] + counts[5] print("4 or 5:", top, round(top / len(survey) * 100, 1))
Output2 14
3 72
4 135
5 79
4 or 5: 214 71.3Of 300 answers, 214, which is 71.3 percent, are 4 or 5. The mean of these scores is 3.93. You can write "mean satisfaction is 3.93", but this sentence quietly assumes that the difference between 4 and 5 equals the difference between 1 and 2. For ordinal data, a more honest summary is the count table and the "share of the top two scores". We will see another measure of the center that fits ordinal data (the median) in lesson 12.
The code below works on a small table of six orders. It looks at the type and chooses the summary itself. Change the value of column and see which lines run:
Change the value of column. Which summary does the code choose, based on the type of the column?
Pick a value; predict the output first, then look.
1from collections import Counter2column = "device"3data = {"device": ["mobile", "desktop", "mobile", "mobile", "desktop", "mobile"],4 "quantity": [2, 1, 1, 3, 1, 2],5 "satisfaction": [4, 5, 4, 2, 5, 4]}6kind = {"device": "categorical", "quantity": "numeric", "satisfaction": "categorical"}7x = data[column]8if kind[column] == "numeric":9 print("Total:", sum(x), "Mean:", round(sum(x) / len(x), 2), "Range:", min(x), "-", max(x))10else:11 value, n = Counter(x).most_common(1)[0]12 print("Most common:", value, "Share (%):", round(n / len(x) * 100, 1))
Most common: mobile Share (%): 66.7
Faded lines didn't run with this value. The code first looks at the kind dictionary: for a numeric column it prints the total, mean, and range; for a categorical column it prints the most common value and its share. Satisfaction is written with numbers, but it is an ordinal category, so the output is the most common score and its share instead of a mean. An analyst does the same: type first, then summary.
Now try the same two summaries on the real file. In the second try you will get an error; don't worry, that error tells you something about the topic of this lesson.
Try it now· not graded; doesn't affect progress
We will see in detail how to deal with empty values in lessons 4 and 19. For now, know this: silently counting an empty cell as 0 pulls the mean down by mistake; skipping it and saying how many values are left is more honest.
A column written with numbers is not necessarily numeric. A postal code, a customer_id number, a product code, or a phone number is nominal: each one gives a name and does not measure an amount. For an identifier column, the meaningful summary is the "number of distinct values", like 524 customers. You see this trap best in an experiment. Someone coded the carriers as 1 (Arrow Express), 2 (Gull Post), 3 (Caravan Freight) and took the mean of the column:
The carriers were coded 1, 2, 3; over 885 orders the mean of this column is 1.87. What does this number tell you?
Remember that the coding is arbitrary: the same carriers could have been numbered 10, 20, 30, and then the "mean" would be 18.7, while the carriers would still be the same carriers. If the result of a calculation depends on how the labels were chosen, that calculation gives information about the labels, not about the data.
This rule has a useful exception. The purchased column in the sessions table is 1 (bought) or 0 (did not buy) for every visit. This is also a label, a nominal "yes/no" variable. But the sum of 0s and 1s gives the number of "yes" values, and the mean gives the share of "yes" values:
import csv with open("sessions.csv", encoding="utf-8") as f: sessions = list(csv.DictReader(f)) bought = [int(s["purchased"]) for s in sessions] print(len(bought), sum(bought), sum(bought) / len(bought))
Output1000 105 0.105Of 1,000 sessions, 105 had a purchase; the mean is 0.105, so 10.5 percent of the sessions turned into a sale. The weekend column in the marketing table is the same: its mean tells you what share of the days are weekend days. This shortcut will be very useful later when you calculate rates (in lessons 5 and 7).
Now use what you learned in a sentence for a report:
You will write the survey satisfaction in one line for the report that goes to the manager. You have 300 answers: 14 people gave 2 points, 72 gave 3, 135 gave 4, 79 gave 5; the mean is 3.93.
Pick an option and see what happens. There are no points; you can try the other options too.
This way of thinking is not special to Bazaar. Think of a high school's student list: student number, grade level (9–12), the area code of the home city, height (cm), number of siblings, and report card letter grade (A, B, C, D, F). The unit of observation is a student. You ask the same three questions of every column; in the Examples section below, the summaries of this table are also given in code.
Choose the type of each column in the high school student list.
For each row, pick its match from the list, then check.
The work of the variable card ends here: next to every column you wrote its type and its fitting summary. In every lesson from now on, you will look at this card before you make a calculation.
In a list of four students, we apply to each column the summary that fits its type: the most common value for the letter grade, mean and range for height, and total for the number of siblings.
from collections import Counter students = [ {"number": 1042, "grade_level": 9, "city_code": 34, "height": 168.5, "siblings": 1, "grade": "B"}, {"number": 1107, "grade_level": 10, "city_code": 6, "height": 175.0, "siblings": 0, "grade": "A"}, {"number": 1093, "grade_level": 9, "city_code": 35, "height": 159.2, "siblings": 2, "grade": "B"}, {"number": 1150, "grade_level": 11, "city_code": 34, "height": 181.4, "siblings": 1, "grade": "C"}, ] print("Number of students:", len(students)) grades = Counter(s["grade"] for s in students) print("Most common grade:", grades.most_common(1)[0]) height = [s[] s students] (, ((height) / (height), 1), , (height), , (height)) siblings = [s[] s students] (, (siblings))
Taking the mean of a category that is coded with numbers. Coding the carriers as 1, 2, 3, finding a mean of 1.87, and saying "the carriers are used in a balanced way" has no basis; if the codes were chosen differently, the result would be different too. The right way: first write down the type of the column; for nominal and ordinal columns use count and share, for numeric columns use total, mean, and range.
Next lesson: We learned who the table describes; but whom does this table represent, and what claim can it support? Where did the data come from?
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.
| Caravan Freight |
| 4 |
OutputNumber of students: 4
Most common grade: ('B', 2)
Mean height: 171.0 Range: 159.2 - 181.4
Total siblings: 4The mean of the number and city_code columns could also be calculated, but an "average student number" like 1098 takes nobody anywhere.
Let's see the line that turns the carriers into numbers and takes their mean next to the count and share of the same column.
import csv from collections import Counter with open("orders.csv", encoding="utf-8") as f: rows = list(csv.DictReader(f)) code = {"Arrow Express": 1, "Gull Post": 2, "Caravan Freight": 3} codes = [code[r["carrier"]] for r in rows] print("Mean carrier code:", round(sum(codes) / len(codes), 2)) for carrier, n in Counter(r["carrier"] for r in rows).most_common(): print(carrier, n, round(n / len(rows) * 100, 1))
OutputMean carrier code: 1.87
Arrow Express 350 39.5
Gull Post 297 33.6
Caravan Freight 238 26.9The first line answers no question; the three lines below it clearly answer "how much is each carrier used?".