Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Data Analysis with Python (pandas, polars, DuckDB)  Module 1 – The data-analysis workflow and your toolkit

What data analysis is: from question to decision

How data analysis turns a question into a decision: the analysis loop, a written metric definition, four kinds of question, and two definitions that disagree.

  • Beginner
  • 25 minutes
  • Examples run with Python 3.14.8, pandas 3.0.6, polars 1.44.2, duckdb 1.5.6 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Describe the analysis loop from the question to the answer people act on
  • Write a metric definition with its numerator, denominator, time window, filters and grain
  • Distinguish descriptive, diagnostic, predictive and prescriptive questions
  • Explain where spreadsheets, pandas, polars and DuckDB each fit in an analyst's work

Two definitions of the same 84 days can point to opposite staffing decisions. Data analysis is the work of answering a question with data, carefully enough that someone can act on the answer. Behind almost every question there is a decision: how many cooks to put on the Saturday shift, whether to keep a new checkout page, which bus route needs a second bus. The analysis is worth doing because that decision is better made with evidence than with a hunch.

The work runs as a loop. You pin down the question and the decision behind it, find the data, clean it, explore it, give an answer with its definition, and explain it to the people who decide. What you learn on the way often sharpens the question, and the loop starts again.

The analysis loops back when the data changes the question

The step that changes answers most comes before any code: writing down exactly what you will measure. This lesson walks through the loop, writes one metric: A number computed from a written definition that fixes what is counted, its denominator, the time window, the filters and what each source row represents. definition in full, and runs 84 days of canteen data through two reasonable definitions of “busy” that point in opposite directions.

The analysis loop: question, data, cleaning, exploration, answer and communication, with arrows back to the question.1. Questionwhat decision does it serve?2. Datawhat does one row stand for?3. Cleaningtypes, gaps, duplicates, a data log4. Explorationsummaries, groups, charts5. Answerthe metric, with its definition6. Communicationthe answer, the evidence, the limitsthe next, sharper questionthe data cannot answer it as asked

The analysis loop, from the decision behind a question to the answer people act on

Text description of the diagram

The diagram shows six steps joined by arrows, from top to bottom.

  1. Question: what decision does it serve?
  2. Data: what does one row stand for?
  3. Cleaning: types, gaps, duplicates and a data log.
  4. Exploration: summaries, groups and charts.
  5. Answer: the metric, with its definition.
  6. Communication: the answer, the evidence and the limits.

Two arrows lead back to step 1. One goes from communication, labelled "the next, sharper question". The other goes from exploration, labelled "the data cannot answer it as asked".

  1. Question. Establish who will decide what, and by when. Ask which answer would change their mind: if no possible answer would, the analysis becomes a report nobody uses.
  2. Data. Establish what exists, who keeps it and how it was collected. Write down what one row of each table stands for before you use it.
  3. Cleaning. Fix what would bend the answer: numbers stored as text, missing values, duplicates, impossible values. Record every change in a data log, so that someone else can repeat it.
  4. Exploration. Summarise, group and plot. Look for what surprises you, because a surprise is either a finding or a data problem, and you need to know which one it is.
  5. Answer. Give the number with its definition and with how sure you are: “34.8 orders per open hour at weekends, over the last 12 weeks, with closed days left out”.
  6. Communication. Lead with the answer and the decision it supports, then the evidence, then the limits. A table or a chart is the evidence; the sentence above it is the message.

The arrows back matter as much as the ones forward. Exploration often shows that the data cannot answer the question as it was asked (a shop records its sales but not how many people walked in, say), and the honest move is to go back to step 1 with a question the data can answer.

Follow the loop on the canteen data and notice the step where a daily comparison becomes an hourly one:

Interactive · stage by stage One canteen question becomes a staffing decision Step through the same 84-day canteen table; watch the question, definition and decision stay connected.
One canteen question becomes a staffing decision, step 6 of 6. Showing Question, Data, Cleaning, Exploration, Answer, Communication. In focus: Communication.QuestionStaffing on weekendsData84 daily rowsCleaning83 open daysExplorationCompare two ratesAnswer34.8 orders per hourCommunicationEvidence and limits

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Question. The decision is whether to roster a second cook on Saturdays and Sundays. A daily total alone does not describe the work of an hour on duty.
  2. Data. The canteen has 84 daily rows. Each records orders and open hours; one Wednesday was closed, so it contributes no open time.
  3. Cleaning. Leave the closed day out of the per-open-day comparison. Keep the original file and record that filter so another analyst can repeat it.
  4. Exploration. Weekdays have 289.0 orders per day and weekends 208.8; per open hour the rates are 24.1 and 34.8. The denominator reverses the ranking.
  5. Answer. For staffing while the counter is open, report the weekend rate of 34.8 orders per open hour with its period, filter and grain.
  6. Communication. The rate supports considering a second cook. It does not settle wages, space or acceptable waiting time; those limits belong beside the recommendation.

The loop keeps the decision visible while the evidence changes. Returning to the question is useful when the original data cannot measure what it asks.

Checkpoint

Check: The analysis loop

  1. One question The till records sales but no footfall. Can this export alone answer whether more visitors bought something?

    Choose one answer.

    Show the answer: One question

    Answer: No; ask for visitor counts or change the question

    Return to the question or obtain the missing denominator before reporting a conversion rate.

The decision chooses what busy needs to mean

Requests reach analysts as vague questions: “How are sales doing?”, “Is the new menu working?”, “Are weekends busier?”. Before you open any file, ask the person who asked:

  • What will you do differently depending on the answer?
  • By when do you need it, and how precise does it have to be?
  • What answer would surprise you?

The canteen owner who asked “are weekends busier?” answers the first question at once: she wants to know whether to roster a second cook on Saturdays and Sundays. That one sentence settles what “busy” has to mean for her: how much work the kitchen has while it is open.

Use the two requests below to choose the unit before calculating a total. The same canteen table can answer both, but the denominator changes.

Decision Work the metric must describe
How many cooks are needed on duty? Orders per open hour.
How many ingredients are needed for a day? Orders per day.

A clear decision prevents a precise calculation from answering the wrong question. Use each request to choose a unit before looking at the matching row.

A metric definition fixes five choices before the calculation

A metric is a number computed the same way every time, from a definition that is written down. A useful definition has five parts:

Part What it settles in the canteen definition
Numerator What you count or add up: orders taken.
Denominator What you divide by, so that groups of different size compare fairly: hours the canteen was open.
Time window Which period counts: the last 12 complete weeks.
Filters Which rows are left out, and why: days the canteen was closed.
grain: What one row of a table represents, such as one order, one item line or one day. A row count measures that unit rather than any other unit. What one row of the data stands for: one row per day.

Every part is a choice that can change the answer. “Monthly active users” sounds precise, yet it is a different number when “active” means opening the app, signing in or placing an order, and again when the month is counted in UTC rather than in local time. Two teams that report “active users” from different definitions end up arguing about numbers that were never comparable.

Key idea

The numerator, denominator, window, filters and grain decide what a metric means; the tool only carries out that definition.

Checkpoint

Check: The five definition parts

  1. One question Two teams use the same active event but one ends its day in UTC and the other at local midnight. Which definition part still differs?

    Choose one answer.

    Show the answer: One question

    Answer: The time window and its boundary

    Write the boundary with the time window. Otherwise the same events can produce different daily counts.

Dividing by days or hours reverses the canteen ranking

The canteen kept one row per day for 12 weeks: the week, the day, how many hours it was open and how many orders it took. On weekdays it opens for 12 hours, on Saturdays and Sundays for 6, and in week 6 it stayed shut on Wednesday for a holiday. The numbers are invented for this lesson, with a fixed random seed so that they never change, but their shape is a common one: shorter opening hours and a busier counter at weekends. Four of the 84 rows:

Daily row Recorded values
Week 1, Mon open_hours = 12, orders = 262.
Week 1, Tue open_hours = 12, orders = 270.
Week 1, Sat open_hours = 6, orders = 202.
Week 6, Wed open_hours = 0, orders = 0.

This program computes both definitions from the same table with pandas, the library most of this track uses:

Orders per day and per open hour, by day type

canteen/busy_pandas.py

# Are weekends busier at the canteen? Two definitions of "busy" on the same 84 days.
import pandas as pd

days = pd.read_csv("canteen_days.csv")  # one row per day: week, day, open_hours, orders
open_days = days[days["open_hours"] > 0]  # the filter: a closed day is not a slow day
weekend = open_days["day"].isin(["Sat", "Sun"])
open_days = open_days.assign(day_type=weekend.map({True: "weekend", False: "weekday"}))

busy = open_days.groupby("day_type").agg(
    days=("day", "size"), orders=("orders", "sum"), open_hours=("open_hours", "sum")
)
busy["per_day"] = (busy["orders"] / busy["days"]).round(1)  # definition A
busy["per_open_hour"] = (busy["orders"] / busy["open_hours"]).round(1)  # definition B
print(busy)

weekdays = days[~days["day"].isin(["Sat", "Sun"])]
print("\nWeekday orders per day if the closed day counted:", round(weekdays["orders"].mean(), 1))

Output

          days  orders  open_hours  per_day  per_open_hour
day_type                                                  
weekday     59   17053         708    289.0           24.1
weekend     24    5011         144    208.8           34.8

Weekday orders per day if the closed day counted: 284.2

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 busy_pandas.py

canteen/canteen_days.csv

week,day,open_hours,orders
1,Mon,12,262
1,Tue,12,270
1,Wed,12,277
1,Thu,12,313
1,Fri,12,288
1,Sat,6,202
1,Sun,6,200
2,Mon,12,292
2,Tue,12,288
2,Wed,12,279
2,Thu,12,304
2,Fri,12,338
2,Sat,6,229
2,Sun,6,199
3,Mon,12,270
3,Tue,12,277
3,Wed,12,250
3,Thu,12,310
3,Fri,12,314
3,Sat,6,232
3,Sun,6,204
4,Mon,12,300
4,Tue,12,251
4,Wed,12,260
4,Thu,12,321
4,Fri,12,351
4,Sat,6,232
4,Sun,6,218
5,Mon,12,289
5,Tue,12,243
5,Wed,12,265
5,Thu,12,292
5,Fri,12,302
5,Sat,6,214
5,Sun,6,213
6,Mon,12,302
6,Tue,12,275
6,Wed,0,0
6,Thu,12,255
6,Fri,12,334
6,Sat,6,209
6,Sun,6,191
7,Mon,12,281
7,Tue,12,276
7,Wed,12,276
7,Thu,12,261
7,Fri,12,318
7,Sat,6,229
7,Sun,6,200
8,Mon,12,287
8,Tue,12,297
8,Wed,12,260
8,Thu,12,282
8,Fri,12,351
8,Sat,6,215
8,Sun,6,196
9,Mon,12,255
9,Tue,12,252
9,Wed,12,251
9,Thu,12,257
9,Fri,12,334
9,Sat,6,236
9,Sun,6,176
10,Mon,12,296
10,Tue,12,268
10,Wed,12,275
10,Thu,12,269
10,Fri,12,347
10,Sat,6,223
10,Sun,6,193
11,Mon,12,286
11,Tue,12,298
11,Wed,12,308
11,Thu,12,291
11,Fri,12,323
11,Sat,6,225
11,Sun,6,186
12,Mon,12,309
12,Tue,12,270
12,Wed,12,275
12,Thu,12,315
12,Fri,12,313
12,Sat,6,205
12,Sun,6,184

It reads the file, keeps the days the canteen was open, labels each day as a weekday or a weekend day, and adds up the days, orders and open hours for each label. The last two columns divide those sums. You do not need to follow every line yet: what matters here is the definition that each line carries out.

The two definitions disagree:

  • Per day (definition A), weekdays win clearly: 289.0 orders against 208.8, about 38 % more.
  • Per open hour (definition B), weekends win: 34.8 orders against 24.1, about 44 % more.

Neither number is a mistake; each one answers a different decision. For ordering ingredients, which are used up per day, definition A is the one that matters. For the owner’s decision, how many cooks the kitchen needs while it is open, definition B is the right one: at weekends the counter is about 44 % busier per hour, so a second cook is worth considering even though the day’s total is lower.

The filter matters as well. The last line counts the closed Wednesday as a weekday with no orders, and the weekday average falls from 289.0 to 284.2. One holiday in 12 weeks moves it by under 2 %, but a month with a 10-day closure in it would pull the average down by about a third. Definition B does not move at all, because the closed day adds neither orders nor open hours.

Follow the sums that all three programs print; the orders stay fixed while only the denominator changes:

Interactive · stage by stage The same orders, two denominators Step through the recorded weekday and weekend sums, then compare their daily and hourly rates.
The same orders, two denominators, step 4 of 4. Showing Weekday sums, Weekend sums, Hourly comparison, Match the decision. In focus: Match the decision.Weekday sums17,053 in 708 hoursWeekend sums5,011 in 144 hoursHourly comparison24.1 versus 34.8Match the decisionStaffing uses hours

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Weekday sums. There are 59 open weekdays, with 17,053 orders in 708 hours. Dividing by 59 gives about 289.0 orders per day.
  2. Weekend sums. There are 24 weekend days, with 5,011 orders in 144 hours. Dividing by 24 gives about 208.8 orders per day.
  3. Hourly comparison. Dividing the same orders by open hours gives 17,053 / 708 = 24.1 and 5,011 / 144 = 34.8, rounded to one decimal place.
  4. Match the decision. Weekdays have more daily orders, but weekends demand more work per hour. Choose the denominator by the staffing or purchasing decision.

The reversal is an arithmetic result of different opening hours. It does not mean that either calculation is defective.

Different opening hours also matter inside one group. Consider a second, tiny invented input from the exercise, separate from the 84-day export: Monday has 300 orders in 12 hours, and Tuesday 60 in 6 hours. Follow their combined rate and the tempting mistake:

Interactive · stage by stage Unequal opening hours give the days different weights Step through two invented weekday rows from the exercise; compare adding the totals with averaging their rates.
Unequal opening hours give the days different weights, step 4 of 4. Showing Day 1, Day 2, Combined rate, Equal-day average. In focus: Equal-day average.Day 1300 orders in 12 hoursDay 260 orders in 6 hoursCombined rate360 orders in 18 hoursEqual-day average17.5 instead of 20

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. The long day. Day 1 has 300 orders in 12 open hours, or 25 orders per hour. Its 12 hours must contribute to the combined workload.
  2. The short day. Day 2 has 60 orders in 6 hours, or 10 orders per hour. It contributes only half as many open hours as day 1.
  3. Divide the totals. Add orders and hours separately. There are 360 orders in 18 hours, so the combined rate is 20 orders per open hour.
  4. The plausible mistake. Averaging 25 and 10 gives 17.5 and treats the 6-hour day as if it had the same exposure as the 12-hour day. Weight the rates by hours or divide the totals.

The combined rate is (300 + 60) / (12 + 6) = 20 orders per open hour. Averaging the daily rates, 25 and 10, would give 17.5 and give the shorter day too much weight. Adding the numerators and denominators first keeps the meaning of an order per open hour when days differ.

Checkpoint

Check: Choose the denominator

  1. One question The weekend has 5,011 orders in 144 open hours. What is its rate rounded to one decimal place?

    Type a number.

    Show the answer: One question

    Answer: 34.8 orders per open hour

    5,011 / 144 = 34.7986…, which rounds to 34.8 orders per open hour.

Three tools agree when their definitions agree

A definition is not tied to a tool. Here is the same calculation in polars, which builds the query from expressions, and in DuckDB, which runs SQL straight on the CSV file:

The same question in polars and in DuckDB

Python (busy_polars.py) · canteen/busy_polars.py

# The same question in polars: filter, label, group, then divide the sums.
import polars as pl

days = pl.read_csv("canteen_days.csv")
busy = (
    days.filter(pl.col("open_hours") > 0)
    .with_columns(
        day_type=pl.when(pl.col("day").is_in(["Sat", "Sun"])).then(pl.lit("weekend")).otherwise(pl.lit("weekday"))
    )
    .group_by("day_type")
    .agg(days=pl.len(), orders=pl.col("orders").sum(), open_hours=pl.col("open_hours").sum())
    .with_columns(
        per_day=(pl.col("orders") / pl.col("days")).round(1),
        per_open_hour=(pl.col("orders") / pl.col("open_hours")).round(1),
    )
    .sort("day_type")
)
print(busy)

Output

shape: (2, 6)
┌──────────┬──────┬────────┬────────────┬─────────┬───────────────┐
│ day_type ┆ days ┆ orders ┆ open_hours ┆ per_day ┆ per_open_hour │
│ ---      ┆ ---  ┆ ---    ┆ ---        ┆ ---     ┆ ---           │
│ str      ┆ u32  ┆ i64    ┆ i64        ┆ f64     ┆ f64           │
╞══════════╪══════╪════════╪════════════╪═════════╪═══════════════╡
│ weekday  ┆ 59   ┆ 17053  ┆ 708        ┆ 289.0   ┆ 24.1          │
│ weekend  ┆ 24   ┆ 5011   ┆ 144        ┆ 208.8   ┆ 34.8          │
└──────────┴──────┴────────┴────────────┴─────────┴───────────────┘

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 busy_polars.py

Python (busy_duckdb.py) · canteen/busy_duckdb.py

# The same question in DuckDB: SQL straight on the CSV file.
import duckdb

busy = duckdb.sql("""
    SELECT CASE WHEN day IN ('Sat', 'Sun') THEN 'weekend' ELSE 'weekday' END AS day_type,
           count(*) AS days,
           sum(orders) AS orders,
           sum(open_hours) AS open_hours,
           round(sum(orders) / count(*), 1) AS per_day,
           round(sum(orders) / sum(open_hours), 1) AS per_open_hour
    FROM 'canteen_days.csv'
    WHERE open_hours > 0
    GROUP BY day_type
    ORDER BY day_type
""")
print(busy)

Output

┌──────────┬───────┬────────┬────────────┬─────────┬───────────────┐
│ day_type │ days  │ orders │ open_hours │ per_day │ per_open_hour │
│ varchar  │ int64 │ int128 │   int128   │ double  │    double     │
├──────────┼───────┼────────┼────────────┼─────────┼───────────────┤
│ weekday  │    59 │  17053 │        708 │   289.0 │          24.1 │
│ weekend  │    24 │   5011 │        144 │   208.8 │          34.8 │
└──────────┴───────┴────────┴────────────┴─────────┴───────────────┘

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 busy_duckdb.py

All three programs print 289.0 and 208.8 orders per day and 24.1 and 34.8 orders per open hour, in three different layouts; polars and DuckDB also print each column’s type under its name. A tool changes how you write a calculation and how fast it runs on large data. It does not change what the numbers mean, which the definition decides, and that is why the definition is written first.

The question type sets the evidence it needs

Questions differ in what they ask of the data, and so in the evidence they need:

Kind The question and the evidence it needs
Descriptive What happened? At the canteen: how many orders did we take on each day of the week last term? It needs a clear definition and clean counts.
Diagnostic Why did it happen? At the canteen: why did Tuesday orders drop after the menu changed? It needs comparisons that rule out other causes: other days, other weeks, the same weeks a year earlier.
Predictive What will happen? At the canteen: how many orders will we take next Saturday? It needs a model of past patterns, and a range rather than a single number.
Prescriptive What should we do? At the canteen: how many cooks should work on Saturday? It needs a prediction, plus the costs and limits: wages, waiting times, space in the kitchen.

Each kind rests on the one before it: a recommendation needs a prediction, and a prediction needs good descriptions. The owner’s question sounds descriptive, but her decision is prescriptive. The per-hour numbers are the evidence, and the decision also weighs what a second cook costs. Most day-to-day analyst work is descriptive and diagnostic, and so is this track. Statistics goes further into uncertainty, and machine learning into prediction.

Checkpoint

Check: Four kinds of question

  1. One question “How many cooks should work on Saturday?” asks for which kind of answer?

    Choose one answer.

    Show the answer: One question

    Answer: Prescriptive, using expected demand and constraints

    A prescriptive answer combines evidence about likely workload with the costs and limits of the available actions.

The grain decides what counting rows counts

The grain of a table is what one of its rows stands for. The canteen’s till could give you three tables about the same Monday:

  • Order items: one row for every item on an order. An order of a tea and two samosas is two rows, one with a quantity of 1 and one with a quantity of 2.
  • Orders: one row per order, with its time and its total.
  • Days: one row per day, like the table in the example.

Ask “how many orders on Monday?” and only the second table answers it by counting rows. Counted from the first, every order with two different items counts twice. So before you analyse a table, write its grain in one sentence and name its row key: The columns that identify one row at the table's stated grain. Repeated keys require investigation unless the table's grain permits them., the columns that identify one row: the order number and the item for the first table, the order number for the second, the week and the day for the third. If two rows share a key, either the grain is not what you thought or the data holds duplicates, and checking that every key is unique is one of the first things to do with any new table.

Compare the two rows of an order for tea and samosas below. The quantity of two samosas belongs to one item line; counting lines does not count physical items or orders.

Table grain Count for that order
One row per distinct item line 2 rows.
One row per order 1 row.

The row key should express that grain. Repeated order numbers are expected across item lines but require investigation in a one-row-per-order export.

Checkpoint

Check: Row grain and keys

  1. One question One order contains a tea line with quantity 1 and a samosa line with quantity 2. How many orders does it represent?

    Type a number.

    Show the answer: One question

    Answer: 1 order

    There is one order, two distinct item lines and three physical items. Each count has a different unit.

Choose the tool from the workload and the way you work

This track uses four kinds of tool, and each has work it does best.

Spreadsheets such as Excel, Google Sheets and LibreOffice Calc show every cell and every formula, which makes them good for small tables, one-off questions and sharing with people who do not code. They get harder to trust as the work grows: a formula copied down thousands of rows can be wrong in one of them without anyone seeing it, and an Excel worksheet stops at 1,048,576 rows.

pandas is the Python DataFrame library used for most of this track. PyPI download counts change over time and include automated installs, so they measure installation traffic rather than the number of people using a tool. It reads files, cleans, groups, joins and reshapes, and it works in memory, so a table has to fit in your computer’s RAM with room left for the copies that some operations make.

polars is a DataFrame library whose core is written in Rust. You describe a calculation with expressions; polars can plan the whole query before running it, spread the work over every processor core and, with its streaming engine, work through data that does not fit in memory, one batch at a time, when the query’s operators support that streaming path.

DuckDB is a SQL database that runs inside your Python program, with no server to install or look after. It queries CSV, Parquet and JSON files and pandas or polars DataFrames directly, and its supported operators can spill to disk, so many workloads can process data larger than memory; check the query’s operators and available disk space.

Answer the table’s questions for the work you need. Its options compare workflows and capacity, with the limits visible:

Interactive · answer and compare Choose a tool for the work you need Answer for your calculation and collaborators. Check memory and operator limits before relying on a larger-than-memory path.
Do collaborators need to edit formulas directly in visible cells?
Do you want this calculation written as the SQL query shown in the lesson?
Will the table and intermediate copies exceed the memory available for this analysis?

Answer the questions above: the table then marks what fits your case and says why the rest does not.

Four workflows compared on syntax, data size and their typical use.
Tool Data size Typical use
Spreadsheet You write: Formulas in cells Mixed Excel allows 1,048,576 rows per sheet; check the actual file and memory needs. Good Small tables that collaborators can inspect and edit cell by cell.
pandas You write: Python operations Mixed The loaded table and working copies normally need to fit in RAM. Good Everyday cleaning, reshaping and analysis in Python.
polars You write: Planned expressions Mixed Streaming can handle larger data; check that the actual query supports its streaming path. Good Expression-based pipelines on large files that you run repeatedly.
DuckDB You write: SQL queries Mixed Disk spilling supports larger-than-memory workloads; operator and disk limits still matter. Good SQL over files and DataFrames inside the analyst’s process.
How the answers decide
  • “Do collaborators need to edit formulas directly in visible cells?” Yes, edit cells: rules out pandas, polars and DuckDB. The direct cell-editing workflow is the spreadsheet’s role in this comparison.
  • “Do you want this calculation written as the SQL query shown in the lesson?” Yes, SQL: rules out Spreadsheet, pandas and polars. DuckDB directly executes the embedded SQL example; the other shown workflows use cells or Python expressions.
  • “Will the table and intermediate copies exceed the memory available for this analysis?” Yes, larger than RAM: rules out pandas and adds a caveat to Spreadsheet, polars and DuckDB. Check actual capacity and operator support. A streaming or spilling path is a capability to validate, not a promise for every query.

The chosen workflow still has to carry out the same written metric definition.

The track teaches pandas first, because most of the code and answers you will meet use it, and then polars and DuckDB.

Audit the definitions before explaining a surprising total

Most wrong answers in analysis come from a short list of mistakes, and every one of them can hide behind code that runs without an error:

  • The wrong grain: counting order items as orders, or averaging daily averages as if every day had the same weight.
  • Double counting after a join: attaching a table with several rows per key repeats the rows of the other table, and every sum over them grows.
  • Silent type changes: numbers read as text, codes such as the ZIP code 02139 losing their leading zero, a missing value turning a column of whole numbers into decimals.
  • Missing treated as zero, or zero as missing: an empty cell means “we don’t know”, not “none”.
  • Dates and time zones: 03/04 is day 3 of month 4 in day-first countries and day 4 of month 3 in the United States, and a day that ends at midnight UTC is not the business’s day in India, which runs 5 hours 30 minutes ahead.
CSV Editor & Viewer Open a CSV file of your own and check what one row stands for before you analyse it. Mock Data Generator Make a practice table with columns you choose, to try a metric definition on data you understand.

Use this two-step audit before interpreting a surprising number. First compare the grain, key, filters and time boundaries; then compare the calculation’s types and units.

Check A signal to investigate
Row count before and after a join A supposedly one-to-one join repeats rows.
Amount and time units Paise mixed with rupees, or business-day boundaries mixed with UTC.

A successful program run only shows that the operations were accepted. It does not establish that the rows and definitions support the decision.

Checkpoint

Check: Mistakes that bend answers

  1. One question A join doubles the row count and the reported order total. What should you inspect before explaining a rise in sales?

    Choose one answer.

    Show the answer: One question

    Answer: Whether the joined table has several rows per key

    Check join cardinality and the grain before treating an inflated sum as business growth.

Practise the decisions

Exercise · Easy · Python

Compute both definitions of a busy day

The canteen keeps one row per day. Each row is a dictionary such as {"day": "Sat", "open_hours": 6, "orders": 210}. Write two functions in busy.py:

  • orders_per_day(days): the orders per open day, for weekdays and for the weekend;
  • orders_per_open_hour(days): the orders per open hour, for weekdays and for the weekend.

Both return a dictionary with the keys "weekday" and "weekend", each value rounded to one decimal place with round(value, 1). Saturday ("Sat") and Sunday ("Sun") are the weekend; every other day is a weekday.

Follow the definition from the lesson: leave out every day with 0 open hours, because a closed day is not a slow day. Each list you are given has at least one open weekday and one open weekend day.

Starter code · busy.py

def orders_per_day(days):
    """Orders per open day for weekdays and for the weekend.

    days is a list of dictionaries such as {"day": "Sat", "open_hours": 6, "orders": 210}.
    Returns {"weekday": ..., "weekend": ...}, each value rounded to one decimal place.
    """
    # Replace this line with your code.
    return {"weekday": 0.0, "weekend": 0.0}


def orders_per_open_hour(days):
    """Orders per open hour for weekdays and for the weekend, rounded to one decimal place."""
    # Replace this line with your code.
    return {"weekday": 0.0, "weekend": 0.0}
The sample tests · test_busy.py
from busy import orders_per_day, orders_per_open_hour

WEEK = [
    {"day": "Mon", "open_hours": 12, "orders": 281},
    {"day": "Tue", "open_hours": 12, "orders": 266},
    {"day": "Wed", "open_hours": 0, "orders": 0},  # closed for a holiday
    {"day": "Thu", "open_hours": 12, "orders": 301},
    {"day": "Fri", "open_hours": 12, "orders": 322},
    {"day": "Sat", "open_hours": 6, "orders": 219},
    {"day": "Sun", "open_hours": 6, "orders": 190},
]

HALF_DAY = [
    {"day": "Mon", "open_hours": 12, "orders": 300},
    {"day": "Tue", "open_hours": 6, "orders": 150},  # opened for half a day
    {"day": "Sat", "open_hours": 6, "orders": 200},
    {"day": "Sun", "open_hours": 6, "orders": 220},
]

UNEVEN_HOURS = [
    {"day": "Mon", "open_hours": 12, "orders": 300},
    {"day": "Tue", "open_hours": 6, "orders": 60},
    {"day": "Sat", "open_hours": 6, "orders": 180},
    {"day": "Sun", "open_hours": 3, "orders": 120},
]


def test_orders_per_day():
    """averages the orders over the open days of each type"""
    assert orders_per_day(WEEK) == {"weekday": 292.5, "weekend": 204.5}


def test_orders_per_open_hour():
    """divides the orders by the hours the canteen was open"""
    assert orders_per_open_hour(WEEK) == {"weekday": 24.4, "weekend": 34.1}


def test_closed_days_are_left_out():
    """gives the same answers when a closed Saturday is added"""
    closed = WEEK + [{"day": "Sat", "open_hours": 0, "orders": 0}]
    assert orders_per_day(closed) == {"weekday": 292.5, "weekend": 204.5}
    assert orders_per_open_hour(closed) == {"weekday": 24.4, "weekend": 34.1}


def test_short_opening_hours():
    """counts a half day as one day but as only 6 open hours"""
    assert orders_per_day(HALF_DAY) == {"weekday": 225.0, "weekend": 210.0}
    assert orders_per_open_hour(HALF_DAY) == {"weekday": 25.0, "weekend": 35.0}


def test_unequal_hours_and_unequal_rates():
    """uses total exposure, not an unweighted mean of the daily rates"""
    assert orders_per_day(UNEVEN_HOURS) == {"weekday": 180.0, "weekend": 150.0}
    assert orders_per_open_hour(UNEVEN_HOURS) == {"weekday": 20.0, "weekend": 33.3}
A hint

Loop over the days once and keep two running totals for each day type: the orders, and the denominator (1 for each open day in orders_per_day, the open hours in orders_per_open_hour). Skip a day when day["open_hours"] == 0, and use day["day"] in ("Sat", "Sun") to tell the weekend from a weekday. Divide at the end, not inside the loop.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Practice that adapts to you

Practise this lesson

19 questions about 9 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 19 Which order connects a question to a decision?

    Choose one answer.

    Show the answer: Question 1 of 19

    Answer: Question, data, cleaning, exploration, answer, communication

    The sequence starts from the decision and can return to an earlier step when the data changes what is answerable.

  2. Question 2 of 19 Exploration shows that two exports use different meanings of “order”. What should happen before combining their totals?

    Choose one answer.

    Show the answer: Question 2 of 19

    Answer: Return to the grain and definition, reconcile them, then recompute

    A surprising result can be a data-definition problem. Reconcile the definition before treating it as a business finding.

  3. Question 3 of 19 Which detail turns “Are weekends busier?” into an analysis that supports a decision?

    Choose one answer.

    Show the answer: Question 3 of 19

    Answer: Whether the kitchen needs a second cook while it is open

    Start with the action: a second cook works by the hour, so the comparison must describe work per open hour.

  4. Question 4 of 19 A buyer orders tomorrow’s ingredients once per day. Which canteen measure best matches that decision?

    Choose one answer.

    Show the answer: Question 4 of 19

    Answer: Orders per day

    The unit should match the action: daily purchasing follows daily orders; hourly staffing follows hourly intensity.

  5. Question 5 of 19 Which list describes a metric rather than its implementation?

    Choose one answer.

    Show the answer: Question 5 of 19

    Answer: Numerator, denominator, time window, filters and grain

    A reproducible definition describes the data and unit; a tool name is not a substitute for those choices.

  6. Question 6 of 19 Two reports count the same orders but one includes closed days in its per-day denominator. Why can their averages differ?

    Choose one answer.

    Show the answer: Question 6 of 19

    Answer: The filter and denominator differ even though the numerator matches

    The closed Wednesday changes the weekday denominator from 59 open days to 60 calendar days, lowering 289.0 to 284.2.

  7. Question 7 of 19 What is the denominator of orders per open hour?

    Choose one answer.

    Show the answer: Question 7 of 19

    Answer: The sum of hours when the canteen was open

    Add the orders and open hours for the group, then divide their sums.

  8. Question 8 of 19 A closed day adds zero orders and zero open hours. What happens to orders per open hour when that row is included?

    Choose one answer.

    Show the answer: Question 8 of 19

    Answer: The rate does not change, because both added totals are zero

    This rate divides totals, so adding (0 orders, 0 hours) leaves the group’s numerator and denominator unchanged.

  9. Question 9 of 19 What should stay unchanged when the canteen calculation moves from pandas to SQL?

    Choose one answer.

    Show the answer: Question 9 of 19

    Answer: The filters, grouping and numerator and denominator

    The same definition leads pandas, polars and DuckDB to 289.0/208.8 per day and 24.1/34.8 per open hour.

  10. Question 10 of 19 pandas prints 83 eligible days while a SQL rewrite prints 84. What is the first semantic check?

    Choose one answer.

    Show the answer: Question 10 of 19

    Answer: Whether both apply open_hours > 0 before grouping

    Reconcile eligible rows and definitions before blaming arithmetic or changing the tool.

  11. Question 11 of 19 Which question is predictive?

    Choose one answer.

    Show the answer: Question 11 of 19

    Answer: How many orders will arrive next Saturday?

    Predictive questions ask what will happen; descriptive questions ask what happened.

  12. Question 12 of 19 Tuesday’s orders fell after a menu change. Which statement is justified by that timing alone?

    Choose one answer.

    Show the answer: Question 12 of 19

    Answer: The fall followed the change; other explanations still need comparison

    A diagnostic answer needs comparisons that address other causes; a before-and-after count by itself is descriptive evidence.

  13. Question 13 of 19 What does the grain of a table specify?

    Choose one answer.

    Show the answer: Question 13 of 19

    Answer: What one row represents

    State the grain before counting, joining or aggregating the rows.

  14. Question 14 of 19 An order-item export contains 1,240 rows. Which quantity is known from that count alone?

    Choose one answer.

    Show the answer: Question 14 of 19

    Answer: 1,240 item lines

    Count distinct order keys for orders and add quantities for physical items. A raw row count measures the grain only.

  15. Question 15 of 19 Which tool directly runs SQL over a CSV inside the analyst’s process?

    Choose one answer.

    Show the answer: Question 15 of 19

    Answer: DuckDB

    DuckDB is useful when the work is naturally expressed as SQL on files or DataFrames.

  16. Question 16 of 19 A collaborator wants to edit a small table’s formulas by hand. Which starting choice fits that need?

    Choose one answer.

    Show the answer: Question 16 of 19

    Answer: A spreadsheet, with the definition still written down

    Choose by the workload and collaboration need. Every tool still requires the same clear metric definition.

  17. Question 17 of 19 Why is a missing amount not automatically zero?

    Choose one answer.

    Show the answer: Question 17 of 19

    Answer: Missing means the value is unknown; zero is a known amount

    Choose a missing-value rule from the data’s meaning and record it rather than silently inventing zero amounts.

  18. Question 18 of 19 Two daily reports agree on events but group them into UTC days and India business days. What must be reconciled?

    Choose one answer.

    Show the answer: Question 18 of 19

    Answer: The time-zone boundary of each day

    Convert and group by the intended business-day boundary before comparing daily totals.

  19. Question 19 of 19 Two open weekdays have 300 orders in 12 hours and 60 orders in 6 hours. What is their combined orders-per-open-hour rate?

    Type a number.

    Show the answer: Question 19 of 19

    Answer: 20 orders per open hour

    Add the totals first: (300 + 60) / (12 + 6) = 360 / 18 = 20. Averaging the daily rates, 25 and 10, gives 17.5 and weights the shorter day too heavily.

Interview questions

Fresher · What is the grain of a table, and why should you write it down before you analyse the table?

The grain is what one row of the table stands for: one order, one item on an order, one customer per day, one sensor reading per minute. Writing it down tells you which columns should identify a row (the key) and what a count of rows means. If a table holds one row per order item and you count rows to get orders, every order with two different items counts twice. The grain also tells you which tables join safely: joining daily totals to order items repeats each daily total on every item, and a sum taken afterwards is inflated. So state the grain in one sentence, name the key, and check that no two rows share the same key before you compute anything.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A product manager asks whether the new checkout page improved conversion. Before you write a query, what do you pin down, and how can two reasonable definitions of conversion give opposite answers?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    Daily active users rose 12 % in the week after a launch while revenue fell 5 %. How do you check that both numbers are right before you try to explain the gap?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Data analysis answers a question well enough that someone can act on it, so find the decision first.
  • The work is a loop: question, data, cleaning, exploration, answer and communication, then a sharper question.
  • Write every metric as a definition: numerator, denominator, time window, filters and grain.
  • Two reasonable definitions can point in opposite directions, as orders per day and orders per open hour did here; the decision chooses the definition.
  • Tools change how you compute a number, not what it means: pandas, polars and DuckDB printed the same answer.

Terms in this lesson

grain
What one row of a table represents, such as one order, one item line or one day. A row count measures that unit rather than any other unit.
metric
A number computed from a written definition that fixes what is counted, its denominator, the time window, the filters and what each source row represents.
row key
The columns that identify one row at the table's stated grain. Repeated keys require investigation unless the table's grain permits them.

Corrections

  • Qualified changing download counts and the limits of streaming and spilling to disk; reworded the first two steps of the analysis loop.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.