Python by example

A path from your first line of Python to the tasks that data and analytics exams set. 35 short steps. Each one shows a pattern on several kinds of data, then gives you two questions to try. Built for students getting ready for technical tests and take-home tasks, often done in Hex.

▸ How to use this page

  1. Start at step 1 if you are new. Each step uses only what came before it. If you know the basics, start at Level 2.
  2. Predict. Before you press Run, guess what comes back.
  3. Run it, then change it. Every box is editable. Reset puts it back. Most examples suggest one thing to change.
  4. Try it yourself. Write your code, store your result in a variable called answer, and press Check. It runs yours and a hidden model answer and compares the two.

Want each idea explained more slowly? Python from zero goes step by step, and the steps here link to its lessons. Doing SQL too? Many steps link to the same question in SQL by example, on the same data.

The code runs in real Python inside your browser. The first time you press Run, it loads Python and pandas, which takes about 10 to 15 seconds. After that each run is quick. Every box starts fresh, so nothing you type can break the next one. All the data is made up.

▸ The path: 35 steps

Six levels. Levels 0 and 1 are plain Python. Most exam questions need Levels 2 and 3. The harder ones add 4 and 5.

0Your first Python

Run a line, store a value, do sums, loop over a list. Start here if you have never written code.

  1. 1Run your first line
  2. 2Name a value: variables
  3. 3Numbers and text are different
  4. 4Maths: + - * / // % and round
  5. 5A first list
  6. 6A first loop

1Core Python for exams

Decisions, lists, text, dictionaries, functions, counting and sorting. No libraries.

  1. 7Decisions: if, elif, else
  2. 8Lists in depth: append, slices, in, sorted, set
  3. 9Text: string methods and f-strings
  4. 10Dictionaries: look things up by name
  5. 11Functions: write a step once, use it many times
  6. 12Comprehensions: a loop in one line
  7. 13Counting: a dictionary, Counter, and CSV without pandas
  8. 14Sorting with a key, and ties

2pandas basics

Read a CSV, look at it, pick columns, filter, sort, count, handle blanks.

  1. 15Read a CSV and take a first look
  2. 16Columns: pick, make and rename
  3. 17Filter rows: masks, &, |, isin, between
  4. 18Sort, and the top N
  5. 19Count values: value_counts, nunique, unique
  6. 20Blanks: isna, fillna, dropna

3Grouping and joining

groupby, several sums at once, merge, pivot tables and buckets.

  1. 21groupby: one number per group
  2. 22Several numbers per group: named agg
  3. 23merge: join tables, and find what is missing
  4. 24pivot_table and crosstab
  5. 25Buckets and labels: np.where, map, pd.cut, np.select

4Dates and order

Dates, change on last month, running totals, ranks, duplicates.

  1. 26Dates: parse, take parts, count by month
  2. 27Change on the last period: shift, diff, pct_change
  3. 28Running totals and rolling averages
  4. 29Rank within a group, and the top N per group
  5. 30Duplicates, and the latest row per group

5JSON and exam tasks

Nested JSON, funnels, clean functions with checks, and a chart with a headline.

  1. 31JSON: nested dictionaries and lists
  2. 32JSON to a table: json_normalize and explode
  3. 33Funnels and retention
  4. 34A clean function with sanity checks
  5. 35A quick chart with a headline title

▸ The practice data

The early steps use short lists typed into the code. From step 13 on, the code reads files. They are the same five made-up worlds as SQL by example: a shop, a music app, a football league, a phone app and job offers. The traps are real: blanks, a duplicate row, customers who never ordered, matches not played yet.

L0 Your first Python

Run a line, store a value, do sums, loop over a list. Start here if you have never written code.

Step 1Run your first lineLevel 0

You know: nothing yet. New: running Python and seeing what it gives back.

Type code in a box and press Run. print() shows whatever you put in the brackets.

print("Hello")
print("Two things,", "one line")
print(2 + 3)

Examples

Shop Say hello

Show the result without running
Printed
Welcome to the shop

Text goes inside quotes. The quotes are not printed.

Try changing it: Change the words inside the quotes and press Run again.

Music Print more than one thing

Show the result without running
Printed
Now playing: Salt Road
Next up: Kite Weather

Commas inside the brackets put a space between the pieces. Each print starts a new line.

Try changing it: Add a third line that prints the song after that: Half Light.

Football Python does the sum for you

Predict first: One line has quotes and one does not. What will each print?

Show the result without running
Printed
3
2 + 1

Without quotes, Python works it out. With quotes, it is just text.

App The last line shows on its own

Show the result without running
Printed
This line is printed
Result
'This last line is shown without print'

In a notebook, the value on the last line of a cell is shown even without print. Hex and this page work the same way.

Try changing it: Put 10 * 3 on the last line instead of the text.

Common mistake

Forgetting the quotes. print(Hello) gives NameError: name 'Hello' is not defined, because without quotes Python looks for something called Hello. Text always needs quotes: print("Hello").

Hex and exams: A Hex Python cell works like these boxes: write code, run it, and the output appears under the cell.

Try it yourself

  1. Music Every Try it yourself ends with a line that starts answer =. Check looks at that value. Here, change the song after answer = to Salt Road, then press Check.

    Hint

    Keep the quotes. Capital S and capital R.

    Show the answer
  2. Shop Make answer hold the result of 17 + 25. Let Python do the sum.

    Hint

    No quotes this time, or you get text and not a number.

    Show the answer

After this step you can run code, print words and numbers, and read the output box.

Step 2Name a value: variablesLevel 0

You know: print. New: storing a value under a name so you can use it again.

name = value stores the value. Use the name anywhere after that.

price = 18.0
quantity = 2
total = price * quantity
print(total)

Examples

Shop Price times quantity

Show the result without running
Printed
36.0

Python reads from the top. By line 3 it knows both names.

Try changing it: Change quantity to 5 and run it again.

Music Names can hold text

Show the result without running
Printed
Salt Road by The Gannets

A variable can hold text as well as numbers.

Jobs Change a value

Predict first: What is salary at the end?

Show the result without running
Result
39000

The right side is worked out first, then stored back under the same name.

App Clear names help

Show the result without running
Result
36

Use lower case and underscores. A grader should know what a name means without asking.

Common mistake

Names care about capital letters. Price and price are two different names, so using the wrong one gives a NameError. And = stores a value; it does not test whether two things are equal. That is ==, in step 3.

Try it yourself

  1. Football The home team scored 2 and the away team scored 1. Make answer the total goals, using the two names.

    Hint

    Add the two names together.

    Show the answer
  2. Jobs An offer starts at 37,000. Add a rise of 1,500 and store the new salary in answer.

    Hint

    Write numbers without commas in code: 37000, not 37,000.

    Show the answer

After this step you can store values, change them and use them in sums.

Step 3Numbers and text are differentLevel 0

You know: variables. New: types. A number and text that looks like a number act differently.

Every value has a type. type(x) tells you which. int(), float() and str() convert.

type(2)        # int: a whole number
type(2.5)      # float: a number with a decimal point
type("2")      # str: text
type(True)     # bool: True or False
int("2") + 1   # turn text into a number

Examples

Shop Four types

Show the result without running
Printed
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

int is a whole number, float has a decimal point, str is text, bool is True or False.

Football Text that looks like a number

Predict first: What will the first print show: 3 or 21?

Show the result without running
Printed
21
3

+ joins text and adds numbers. Convert first.

Music Put a number inside text

Show the result without running
Printed
215 seconds

To join a number onto text with +, turn it into text with str().

Try changing it: Remove str( and its bracket. Read the error.

App Comparisons give True or False

Show the result without running
Printed
True
False
True

== tests equal, != tests not equal. The answer is a bool.

Common mistake

Numbers read from a file or typed by a user often arrive as text. "2" + "1" is "21", and "9" > "10" is True because text is compared letter by letter. Convert with int() or float() first.

Try it yourself

  1. Football home and away hold scores as text. Store their total as a number in answer.

    Hint

    int(home) + int(away)

    Show the answer
  2. Music Make answer the text 215 seconds, built from the number in length.

    Hint

    str(length) + " seconds". Mind the space before seconds.

    Show the answer

After this step you can tell int, float, str and bool apart and turn one into another.

Step 4Maths: + - * / // % and roundLevel 0

You know: numbers. New: the maths operators and rounding.

Python is a calculator. / always gives a decimal, // drops it, % gives the remainder.

7 + 2     # 9
7 - 2     # 5
7 * 2     # 14
7 / 2     # 3.5
7 // 2    # 3, whole times
7 % 2     # 1, what is left over
7 ** 2    # 49, to the power
round(3.14159, 2)   # 3.14

Examples

Shop Add VAT and round

Show the result without running
Result
109.47

round(x, 2) gives two decimals. Round at the end, not in the middle.

Try changing it: Try round(with_vat) with no 2. What changes?

Music Seconds to minutes

Predict first: What will each line print?

Show the result without running
Printed
3.5833333333333335
3
35

215 seconds is 3 minutes and 35 seconds.

Jobs A percentage rise

Show the result without running
Result
6.2

Change divided by the old value, times 100. This shape comes up in almost every data exam.

Football Brackets change the answer

Predict first: Which line is the average of 2, 2 and 3?

Show the result without running
Printed
5.0
2.3333333333333335

Multiply and divide happen before add and subtract. Brackets go first.

Common mistake

Missing brackets in an average. a + b / 2 halves only b. Write (a + b) / 2.

Try it yourself

  1. Shop A Chef Knife costs 59.0. A customer buys 3 with 10% off. Store the amount paid, rounded to 2 decimals, in answer.

    Hint

    10% off means paying 0.9 of the price.

    Show the answer
  2. Music A song is 287 seconds long. Store the number of whole minutes in answer.

    Hint

    Whole minutes: //.

    Show the answer

After this step you can work out totals, averages, percentages and minutes from seconds.

Step 5A first listLevel 0

You know: variables and maths. New: a list holds many values under one name.

Square brackets make a list. len, sum, max and min work on the whole list.

goals = [0, 2, 3, 1]
len(goals)     # how many: 4
sum(goals)     # total: 6
max(goals)     # biggest: 3
goals[0]       # the first item
goals[-1]      # the last item

Examples

Shop How many, and the total

Show the result without running
Printed
5
307.49

One name, five values.

Music First and last

Predict first: Which song is queue[1]?

Show the result without running
Printed
Salt Road
Ferry Home

Counting starts at 0. -1 counts from the end.

Football Biggest and smallest

Show the result without running
Printed
3 0

max and min read the whole list.

Jobs An average from a list

Show the result without running
Result
46125.0

Average is total divided by how many. There is no built-in mean here, so you build it.

Common mistake

The first item is [0], not [1]. And asking for an item past the end, like queue[10] on a list of four, gives IndexError: list index out of range.

Try it yourself

  1. Football Store the total number of goals in the list in answer.

    Hint

    One word does it.

    Show the answer
  2. Music Store the first song in the queue in answer.

    Hint

    Counting starts at 0.

    Show the answer

After this step you can make a list and get its length, total, biggest, smallest and any item.

Step 6A first loopLevel 0

You know: lists. New: for does the same step for every item.

for item in a_list: then an indented block. The block runs once per item.

total = 0
for g in [0, 2, 3, 1]:
    total = total + g     # indented: runs for every item
print(total)              # not indented: runs once, after

Examples

Music Print every song

Show the result without running
Printed
Salt Road
Kite Weather
Half Light

song holds a different item each time round.

Try changing it: Add a second indented line: print("---").

Shop Work something out for each item

Show the result without running
Printed
89.0 109.47
45.5 55.96
120.0 147.6

Each line shows a price and the price with VAT.

Football Build a running total

Predict first: How many lines will print, and what is the last one?

Show the result without running
Printed
so far: 0
so far: 2
so far: 5
so far: 6
so far: 8
Result
8

Start at 0 before the loop. Add each item inside the loop.

Jobs Monthly pay for each salary

Show the result without running
Printed
33000 a year is 2750 a month
37000 a year is 3083 a month
61000 a year is 5083 a month

The loop name can be anything. Short names are fine for short loops.

Common mistake

Putting total = 0 inside the loop. It resets to 0 every time, so you end with only the last item. Set the starting value once, before the loop.

Try it yourself

  1. Music Finish the loop so that total ends up as the sum of all the seconds. Then set answer = total.

    Hint

    Inside the loop: total = total + s

    Show the answer
  2. Shop Use a loop to multiply all the quantities together. Store the result in answer.

    Hint

    Start at 1, not 0. Anything times 0 is 0.

    Show the answer

After this step you can walk through a list and build up a total as you go.

Level 0 of 5 done. You can now run code, name values, do sums, and repeat a step for every item in a list.

L1 Core Python for exams

Decisions, lists, text, dictionaries, functions, counting and sorting. No libraries.

Pure Python, no libraries. Many timed tests ban pandas, so this level uses only what comes with Python. Step 13 reads a real CSV file the no-pandas way.

Step 7Decisions: if, elif, elseLevel 1

You know: loops and True or False. New: doing something only when a test passes.

if runs its block when the test is True. elif tries the next test. else catches the rest.

if price > 100:
    label = "premium"
elif price > 40:
    label = "mid"
else:
    label = "budget"

Examples

Shop Label a price

Show the result without running
Printed
premium

Python stops at the first test that passes.

Try changing it: Change price to 45.5, then to 18.0.

Football Who won?

Show the result without running
Result
'draw'

home, away = 2, 2 sets two names in one line.

Music Count with if inside a loop

Predict first: How many skips?

Show the result without running
Result
2

A play under 30 seconds is a skip. Two levels of indent: one for the loop, one for the if.

Jobs Two tests at once: and, or

Show the result without running
Printed
True
True

and needs both. or needs one.

App Stop at the first match

Show the result without running
Printed
found at position 2

break leaves the loop at once.

Common mistake

Tests in the wrong order. Put elif price > 40 before if price > 100 and every premium item is labelled mid, because Python stops at the first test that passes. Go from the narrowest test to the widest.

Try it yourself

  1. Jobs Make answer the text high if salary is 50,000 or more, and standard if not.

    Hint

    "Or more" means >=.

    Show the answer
  2. Music A full play is 30 seconds or more. Count the full plays and store the count in answer.

    Hint

    A loop, an if with >= 30, and a counter that starts at 0.

    Show the answer

After this step you can label values, count the ones that pass a test, and stop a loop early.

Step 8Lists in depth: append, slices, in, sorted, setLevel 1

You know: lists, loops and if. New: building a list, cutting a slice, and removing repeats.

append adds to the end. [a:b] cuts a slice. in tests membership. set drops repeats.

kept = []
for x in items:
    if x > 40:
        kept.append(x)
items[:3]          # first three
items[-3:]         # last three
"x" in items       # True or False
sorted(set(items)) # unique values, sorted

Examples

Shop Build a list in a loop

Show the result without running
Result
[89.0, 45.5, 120.0]

Start with an empty list, append the ones you keep.

Music Slices

Predict first: How many songs does queue[1:3] give?

Show the result without running
Printed
['Salt Road', 'Kite Weather']
['Kite Weather', 'Half Light']
['Ferry Home', 'Glass Tide']

[1:3] starts at position 1 and stops before position 3.

Football Is it in the list?

Show the result without running
Printed
True
False

in gives True or False. It checks exact text.

App Unique values

Show the result without running
Printed
{'android', 'web', 'ios'}
3
['android', 'ios', 'web']

A set keeps one of each. Its order is not fixed, so sort it before you show it.

Jobs sorted against .sort()

Show the result without running
Printed
[33000, 37000, 53500, 61000]
[61000, 33000, 53500, 37000]
[33000, 37000, 53500, 61000]

sorted() gives a new list. .sort() changes the list itself.

Common mistake

x = x.sort(). .sort() changes the list and gives back None, so x becomes None. Use x.sort() on its own line, or x = sorted(x).

Try it yourself

  1. Music Store the last three songs of the queue, in order, in answer.

    Hint

    A slice with a negative start.

    Show the answer
  2. Shop Build a list of the prices over 40, in the same order. Store it in answer.

    Hint

    Empty list, loop, if, append.

    Show the answer

After this step you can build a filtered list, take the first or last few items and find unique values.

Step 9Text: string methods and f-stringsLevel 1

You know: text, lists and loops. New: cleaning text and building it with f-strings.

Methods like .strip(), .lower() and .split() give back new text. An f-string puts values inside text.

s = "  Aoife BYRNE "
s.strip()           # "Aoife BYRNE"
s.strip().title()   # "Aoife Byrne"
s.lower()           # lower case
"a,b,c".split(",")  # ["a", "b", "c"]
s.replace("A", "E")
s.startswith("A")
f"{name} paid {amount:,.2f}"

Examples

Shop Tidy messy names

Show the result without running
Result
['Aoife Byrne', 'Cian Walsh', 'Niamh Kelly']

Methods chain left to right: strip the spaces, then fix the capitals.

Jobs f-strings for money and percentages

Show the result without running
Printed
Data offer: €52,000
Monthly: €4,333.33
Rise: 6.2%

:, adds thousands commas. .2f gives two decimals. .1% turns 0.0625 into 6.2%.

Try changing it: Change .2f to .0f.

App Split a line into parts

Show the result without running
Printed
2025-01-03
4
onboarding_done

split gives a list. Three names on the left take the three parts. time[:10] slices text like a list.

Music Search inside text

Predict first: Will Harbour Lights be found?

Show the result without running
Result
['Half Light', 'Harbour Lights']

Lower-case both sides so the search ignores capitals.

Shop Part of an email address

Show the result without running
Printed
aoife
example.com

A common exam step: split on a character and keep one side.

Common mistake

Expecting a method to change the text in place. name.strip() on its own line does nothing to name. Store it: name = name.strip().

Try it yourself

  1. Shop Clean the name: no spaces at either end, and capital letters only at the start of each word. Store it in answer.

    Hint

    .strip() then .title().

    Show the answer
  2. Jobs Build the text Data offer: €52,000 with an f-string, from family and salary. Store it in answer.

    Hint

    Inside the braces: {salary:,}.

    Show the answer

After this step you can tidy names, split a line into parts and print a neat sentence with numbers in it.

Step 10Dictionaries: look things up by nameLevel 1

You know: lists and text. New: a dictionary maps keys to values.

Curly brackets make a dictionary of key: value pairs. Look up with d[key], or d.get(key, default) when it might be missing.

product = {"name": "Chef Knife", "price": 59.0}
product["price"]             # look up
product.get("discount", 0)   # 0 if there is no such key
product["stock"] = 12        # add or change
for key, value in product.items():
    print(key, value)

Examples

Shop Look up a price

Show the result without running
Result
59.0

Faster and clearer than searching a list.

Jobs A default for a missing key

Show the result without running
Printed
3000
0

.get gives the default instead of an error.

Try changing it: Change the last line to print(bonus["Sales"]) and read the error.

Music Loop over keys and values

Show the result without running
Printed
Salt Road 9
Kite Weather 6
Half Light 4
total: 19

.items() gives pairs. .values() gives just the values.

Football Nested dictionaries

Predict first: Was it a draw?

Show the result without running
Printed
Riverside Rovers
True

Chain the lookups from the outside in. JSON from an API looks just like this.

Common mistake

Looking up a key that is not there: bonus["Sales"] gives KeyError: 'Sales' and stops the code. Use .get(key, default), or test first with if key in bonus.

Try it yourself

  1. Shop Add 5 to the stock of Puzzle 1000. Store the whole dictionary in answer.

    Hint

    stock["Puzzle 1000"] = stock["Puzzle 1000"] + 5

    Show the answer
  2. Jobs Store the company's city in answer.

    Hint

    Two lookups: offer["company"] first.

    Show the answer

After this step you can look up a value, give a default when a key is missing, and read nested data.

Step 11Functions: write a step once, use it many timesLevel 1

You know: if, loops and dictionaries. New: wrapping steps in a function with def.

def names a block of steps. return hands a value back to whoever called it.

def name(arg1, arg2=10):
    """One line on what it does."""
    result = arg1 * arg2
    return result

name(3)        # 30
name(3, 2)     # 6

Examples

Shop Price with VAT

Show the result without running
Printed
109.47
14.99

rate=0.23 is a default. Pass a value to change it.

Football Points for a result

Show the result without running
Result
[3, 1, 0]

A function can return from more than one place.

Music A function that returns True or False

Show the result without running
Printed
True
False
True

Name it like a question when it returns True or False.

Jobs print is not return

Predict first: What will m be?

Show the result without running
Printed
4000
m is None

The function prints 4000 but hands back nothing, so m is None.

Common mistake

Printing inside a function instead of returning. It looks right on screen, but the caller gets None and the next step breaks. Return the value; print it outside if you want to see it.

Try it yourself

  1. Football Write result(home, away) that returns H, D or A. Then store [result(2, 1), result(0, 0), result(1, 3)] in answer.

    Hint

    if, elif, else, each with a return.

    Show the answer
  2. App Write conversion(converted, total) that returns the percentage rounded to 1 decimal, and 0 when total is 0. Store [conversion(10, 36), conversion(0, 0)] in answer.

    Hint

    Test for total == 0 first and return 0. Percentage: 100 * converted / total.

    Show the answer

After this step you can write a small function, give it defaults, and test it on a few inputs.

Step 12Comprehensions: a loop in one lineLevel 1

You know: loops, if, lists and dictionaries. New: the short way to build a list or dictionary.

[expression for item in items if test] builds a list. Curly brackets with key: value build a dictionary.

[p * 1.23 for p in prices]               # change every item
[p for p in prices if p > 40]            # keep some items
{k: v / 12 for k, v in salaries.items()} # a dictionary

Examples

Shop The loop and the one-liner

Show the result without running
Printed
[109.47, 55.96, 147.6]
[109.47, 55.96, 147.6]

Same result. Read the one-liner as "round p times 1.23, for each p in prices".

Music Keep only some items

Show the result without running
Result
[172, 305, 203, 175]

The if at the end filters.

Jobs A dictionary comprehension

Show the result without running
Result
{'Data': 4333, 'Design': 3917, 'Sales': 3000}

Monthly pay for each family, in one line.

Football Change some items, keep all

Predict first: How many items will the new list have?

Show the result without running
Result
['blank', 'scored', 'scored', 'scored', 'scored']

An if with an else goes before the for. It changes items but keeps them all.

Common mistake

Putting the if in the wrong place. [x for x in xs if x > 0] filters. [x if x > 0 else 0 for x in xs] keeps every item. An if with no else before the for is a SyntaxError.

Try it yourself

  1. Music Store a list of the titles that start with S, in capitals, in answer.

    Hint

    t.upper() for each t, with if t.startswith("S").

    Show the answer
  2. Jobs Build a dictionary from family to salary, leaving out any salary that is None. Store it in answer.

    Hint

    if s is not None at the end.

    Show the answer

After this step you can turn a four-line loop into one readable line.

Step 13Counting: a dictionary, Counter, and CSV without pandasLevel 1

You know: dictionaries, loops and .get. New: counting things, and reading a CSV file with only the standard library.

Count by hand with d[x] = d.get(x, 0) + 1, or let Counter do it. csv.DictReader reads each row as a dictionary of text.

counts = {}
for x in items:
    counts[x] = counts.get(x, 0) + 1

from collections import Counter
Counter(items).most_common(3)

import csv
with open("orders.csv") as f:
    rows = list(csv.DictReader(f))   # every value is text

Examples

Football Count by hand

Show the result without running
Result
{'H': 3, 'D': 2, 'A': 1}

The first time a key is seen, .get gives 0.

App Counter does it for you

Show the result without running
Printed
Counter({'android': 3, 'web': 2, 'ios': 1})
[('android', 3)]

most_common(n) gives the top n as (value, count) pairs.

Shop Read a CSV with no pandas

Predict first: Is quantity in the first row 1 or "1"?

Show the result without running
Printed
70 rows
{'order_id': '1', 'customer_id': '15', 'product_id': '1', 'quantity': '1', 'order_date': '2025-01-03', 'status': 'delivered', 'discount': ''}
Result
Counter({'delivered': 57, 'returned': 8, 'cancelled': 5})

Each row is a dictionary. The numbers are text: look at the quotes round them.

Music Most played songs

Show the result without running
Result
[('5', 29), ('4', 18), ('1', 14)]

The same question as GROUP BY with ORDER BY and LIMIT in SQL.

Jobs Add up, not just count

Show the result without running
Result
{'Sales': 212500,
 'Data': 613000,
 'Product': 795500,
 'Design': 489500,
 'Engineering': 228500}

continue skips to the next row. A blank cell in a CSV is empty text, not None.

Common mistake

Comparing or adding CSV values without converting them. From csv, "9" > "10" is True and "2" + "1" is "21". Wrap numbers in int() or float().

Hex and exams: If an exam says no pandas, it usually means the standard library only: csv, json, collections, datetime. Practise both ways.

Try it yourself

  1. Football Using csv (no pandas), count home wins, draws and away wins among played matches. Store a dictionary like {"H": 0, "D": 0, "A": 0} in answer. Matches not played yet have empty goals.

    Hint

    Skip rows where home_goals == "". Convert goals with int before comparing.

    Show the answer
  2. App From events.csv, store the three most common event names with their counts, most common first, as Counter's most_common gives them.

    Hint

    Counter(r["event_name"] for r in rows).most_common(3)

    Show the answer

After this step you can count anything in a file without pandas, which many timed tests ask for.

Step 14Sorting with a key, and tiesLevel 1

You know: lists, dictionaries and functions. New: lambda, a one-line function, to tell sorted what to sort by.

sorted(items, key=...) sorts by whatever the key gives back. Return a tuple to break ties.

sorted(rows, key=lambda r: r["price"])                  # smallest first
sorted(rows, key=lambda r: r["price"], reverse=True)    # biggest first
sorted(rows, key=lambda r: (-r["points"], r["name"]))   # points down, then name A to Z
max(rows, key=lambda r: r["price"])                     # the whole row with the top price

Examples

Shop Sort records by one field

Show the result without running
Result
['Rain Jacket', 'Chef Knife']

lambda p: p["price"] means: for each p, sort by its price.

Music The key with the biggest value

Predict first: Will both lines print the same song?

Show the result without running
Printed
Glass Tide
Salt Road

max(plays) alone compares the keys as text. key=plays.get compares the values.

Jobs Sort a dictionary by value

Show the result without running
Result
[('Product', 55800),
 ('Data', 52400),
 ('Design', 47100),
 ('Sales', 36500)]

.items() gives (key, value) pairs. kv[1] is the value.

Football Break ties with a tuple

Show the result without running
Result
[('Harbour United', 14, 8),
 ('Riverside Rovers', 14, 5),
 ('Shannon Celtic', 14, 5),
 ('Claddagh Town', 11, 2)]

Points high to low, then goal difference high to low, then name A to Z. A minus sign flips a number.

Common mistake

Sorting numbers stored as text. sorted(["9", "10", "100"]) gives ["10", "100", "9"]. Convert first, or use key=int.

Try it yourself

  1. App Store the user_id with the most sessions in answer.

    Hint

    max with key=sessions.get

    Show the answer
  2. Jobs Store the family names sorted by salary, highest first. Break ties A to Z.

    Hint

    key=lambda o: (-o[1], o[0]), then keep just the names.

    Show the answer

After this step you can sort records by any field, break ties, and find the biggest by a rule.

Level 1 of 5 done. You can now solve the plain-Python questions that timed tests set when pandas is not allowed.

L2 pandas basics

Read a CSV, look at it, pick columns, filter, sort, count, handle blanks.

From here on, pandas is loaded. Every box starts with import pandas as pd and import numpy as np already done, like the first cell of a notebook. In your own notebook or Hex project, put those two lines in the first cell.

Step 15Read a CSV and take a first lookLevel 2

You know: lists, dictionaries and reading a CSV by hand. New: pandas, which reads a CSV into a table called a DataFrame.

pd.read_csv loads a file. head, shape, dtypes, info and describe tell you what you have.

import pandas as pd
df = pd.read_csv("orders.csv")
df.head()        # first 5 rows
df.shape         # (rows, columns), no brackets after it
df.dtypes        # the type of each column
df.info()        # types and how many values are not blank
df.describe()    # quick stats for the number columns

Examples

Shop The first five rows

Show the result without running
Result: DataFrame, 5 rows, 7 columns
order_idcustomer_idproduct_idquantityorder_datestatusdiscount
115112025-01-03deliveredNaN
215222025-01-09deliveredNaN
33512025-01-13deliveredNaN
431112025-01-14deliveredNaN
5101212025-01-18deliveredNaN

The bold numbers down the left are the index: pandas' row labels. They start at 0.

Try changing it: Try orders.head(10), then orders.tail(3).

Music How big is it?

Show the result without running
Printed
(170, 5)
170 rows
['stream_id', 'listener_id', 'song_id', 'streamed_on', 'seconds_played']

shape is a pair: rows, then columns.

Football What type is each column?

Predict first: home_goals holds whole numbers. What type will pandas give it?

Show the result without running
Result: Series, 6 rows
match_idint64
match_dateobject
home_team_idint64
away_team_idint64
home_goalsfloat64
away_goalsfloat64

Goals are whole numbers, but pandas stores them as float64. A blank (a match not played yet) cannot sit in a whole-number column, so pandas uses decimals. Dates come in as object, which means text.

App info: types and blanks together

Show the result without running
Printed
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 36 entries, 0 to 35
Data columns (total 5 columns):
 #   Column       Non-Null Count  Dtype 
---  ------       --------------  ----- 
 0   user_id      36 non-null     int64 
 1   signup_date  36 non-null     object
 2   platform     36 non-null     object
 3   country      36 non-null     object
 4   referrer     29 non-null     object
dtypes: int64(1), object(4)
memory usage: 936.0+ bytes

Non-Null Count shows blanks at a glance: referrer has fewer than 36.

Jobs Quick stats on one column

Show the result without running
Result: Series, 8 rows
base_salary
count44.0
mean53159.0909
std15659.8185
min29500.0
25%41375.0
50%48500.0
75%64125.0
max92000.0

count is 44, not 45: one salary is blank. Stats skip blanks.

Common mistake

Brackets on shape. df.shape() gives TypeError: 'tuple' object is not callable. shape, dtypes and columns have no brackets. head(), info() and describe() do.

Hex and exams: In a Hex Python cell, as in any notebook, the last line is shown as output. A dataframe on the last line shows as a table you can scroll. SQL cell results in Hex are dataframes too, so these same tools work on them.

Try it yourself

  1. Jobs How many rows does companies.csv have? Store the number in answer.

    Hint

    len(companies) or companies.shape[0].

    Show the answer
  2. Music Store the longest single play, the biggest seconds_played in streams.csv, in answer.

    Hint

    Pick the column, then .max().

    Show the answer

After this step you can load a file and say how many rows it has, what the columns are and what type each one is.

Step 16Columns: pick, make and renameLevel 2

You know: DataFrames and maths. New: choosing columns and making new ones.

One column is df["a"]. Several is df[["a", "b"]]. Make a column by setting it.

df["col_a"]                         # one column: a Series
df[["col_a", "col_b"]]              # several: a DataFrame
df["new"] = df["col_a"] * 2         # a new column, row by row
df = df.rename(columns={"old": "new_name"})
df = df.drop(columns=["col_c"])

Examples

Shop Prices with VAT added

Show the result without running
Result: DataFrame, 12 rows, 3 columns
namepriceprice_with_vat
Trail Runner Shoes89.0109.47
Camping Stove45.555.96
Rain Jacket120.0147.6
Board Game: Harbour34.9943.04
Puzzle 100018.022.14
Card Game: Gulls12.515.38
Chef Knife59.072.57
Cast Iron Pan42.051.66
Coffee Grinder75.092.25
Novel: Low Tide14.9918.44
Cookbook: Brown Bread24.029.52
Atlas of Islands38.046.74

The sum runs on every row at once. No loop needed.

Football Total goals in each match

Predict first: What will total_goals be for a match not played yet?

Show the result without running
Result: DataFrame, 6 rows, 4 columns
match_idhome_goalsaway_goalstotal_goals
24250.03.03.0
25262.01.03.0
2627NaNNaNNaN
2728NaNNaNNaN
2829NaNNaNNaN
2930NaNNaNNaN

Maths with a blank gives a blank (NaN). The postponed matches have no total.

Music Song length in minutes

Show the result without running
Result: DataFrame, 5 rows, 3 columns
titlelength_secminutes
Salt Road2654.4
Kite Weather2013.4
Half Light2033.4
Ferry Home1923.2
Glass Tide2494.2

In Python, / always keeps the decimals. SQLite would drop them.

App Glue text columns together

Show the result without running
Result: DataFrame, 5 rows, 2 columns
user_idsegment
1web / DE
2android / IE
3web / IE
4web / DE
5web / UK

+ joins text columns, row by row.

Jobs Rename, then work out a new column

Show the result without running
Result: DataFrame, 5 rows, 3 columns
offer_idsalarymonthly
133000.02750.0
237000.03083.0
361000.05083.0
453500.04458.0
574000.06167.0

rename gives back a new table, so store it.

Common mistake

One pair of brackets for several columns. df["name", "price"] gives a KeyError. A list of columns needs two pairs: df[["name", "price"]].

Try it yourself

  1. Music Return a table of each listener's name and plan, with plan renamed subscription. This one checks the column names too.

    Hint

    Pick two columns, then .rename(columns={...}).

    Show the answer
  2. Shop Return a table of each product's name and its price in cent (price times 100).

    Hint

    Make the column, then pick the two you need.

    Show the answer

After this step you can keep only the columns you need and add worked-out columns.

Step 17Filter rows: masks, &, |, isin, betweenLevel 2

You know: columns and True or False. New: keeping only the rows that pass a test.

A test on a column gives True or False for every row. Put it in square brackets to keep the True rows.

df[df["col"] == "x"]
df[(df["a"] > 10) & (df["b"] == "y")]     # and
df[(df["a"] > 10) | (df["b"] == "y")]     # or
df[df["col"].isin(["x", "y"])]            # one of these
df[~df["col"].isin(["x", "y"])]           # not one of these
df[df["col"].between(10, 20)]             # both ends included
df[df["text"].str.startswith("S")]

Examples

Shop Delivered orders of two or more items

Show the result without running
Result: DataFrame, 22 rows, 7 columns
order_idcustomer_idproduct_idquantityorder_datestatusdiscount
1215222025-01-09deliveredNaN
67171122025-01-21deliveredNaN
111213222025-01-28deliveredNaN
272831222025-03-01deliveredNaN
293018422025-03-03deliveredNaN
303151032025-03-07deliveredNaN
3132111122025-03-09deliveredNaN
323313822025-03-20delivered10.0
394012822025-04-06delivered5.0
40415522025-04-08deliveredNaN
43449332025-04-16delivered5.0
464710622025-04-21deliveredNaN
474816122025-04-22delivered5.0
484931122025-04-25deliveredNaN
515251222025-05-08deliveredNaN
525312722025-05-10deliveredNaN
535413232025-05-10deliveredNaN
545510832025-05-13delivered5.0
55563332025-05-14delivered5.0
57586832025-06-01deliveredNaN
606111022025-06-04deliveredNaN
69705522025-04-08deliveredNaN

& means both tests must pass. Each test goes in its own brackets.

Music Look at the mask itself

Show the result without running
Printed
[True, False, False, False, False, False, False, False]
Result: DataFrame, 4 rows, 4 columns
song_idtitleartist_idlength_sec
01Salt Road1265
910Slow Rain4152
1516Static Bloom6218
1920Soft Focus8215

The mask is just a column of True and False. Filtering keeps the True rows.

Jobs Data or Design offers over 50,000

Show the result without running
Result: DataFrame, 10 rows, 8 columns
offer_idcompany_idjob_familylevelbase_salaryoffered_ataccepted_atstatus
452DataSenior74000.02023-02-062023-02-10accepted
24255DataSenior64500.02023-09-222023-10-02accepted
25262DataSenior83000.02023-12-052023-12-17accepted
27287DataMid54500.02024-01-312024-02-01accepted
28298DesignSenior64000.02024-01-312024-02-03accepted
35363DataMid57000.02024-05-122024-05-13accepted
363710DesignSenior68000.02024-05-262024-06-05accepted
40411DesignSenior68500.02024-09-222024-10-02accepted
424310DesignSenior74000.02024-12-082024-12-11accepted
43448DataSenior75000.02024-12-212024-12-27accepted

isin is a short way to write several ORs on one column.

Football Matches in September 2024

Show the result without running
Result: DataFrame, 12 rows, 6 columns
match_idmatch_datehome_team_idaway_team_idhome_goalsaway_goals
15162024-09-07342.05.0
16172024-09-07243.00.0
17182024-09-07121.01.0
18192024-09-14423.02.0
19202024-09-14263.01.0
20212024-09-14152.01.0
21222024-09-21540.01.0
22232024-09-21432.01.0
23242024-09-21521.01.0
24252024-09-28310.03.0
25262024-09-28512.01.0
26272024-09-2863NaNNaN

Dates stored as YYYY-MM-DD text sort and compare correctly, even before you convert them.

App OR needs brackets

Predict first: Will the two counts match?

Show the result without running
Printed
15
15

The extra brackets make the OR happen first. The isin version says the same thing more clearly.

Common mistake

Using and or or between masks. They give ValueError: The truth value of a Series is ambiguous. Use & and |, and put brackets round each test, because & is worked out before ==.

Try it yourself

  1. Jobs Return offer_id and base_salary for Junior offers paying from 35,000 to 40,000, both ends included.

    Hint

    level == "Junior" and .between(35000, 40000).

    Show the answer
  2. Shop Find customers in Cork or Galway who signed up before 1 November 2024. Return name and city.

    Hint

    isin for the cities, and signup_date < "2024-11-01".

    Show the answer

After this step you can filter on one test or several, on lists of values and on ranges.

Step 18Sort, and the top NLevel 2

You know: filtering and sorted() on lists. New: sorting a whole table.

sort_values sorts by one column or several. Add .head(n) for the top n.

df.sort_values("col", ascending=False).head(5)
df.sort_values(["a", "b"], ascending=[True, False])
df.nlargest(5, "col")

Examples

Shop The three dearest products

Show the result without running
Result: DataFrame, 3 rows, 4 columns
product_idnamecategoryprice
23Rain JacketOutdoor120.0
01Trail Runner ShoesOutdoor89.0
89Coffee GrinderKitchen75.0

Biggest first needs ascending=False.

Music nlargest does both steps

Show the result without running
Result: DataFrame, 3 rows, 4 columns
song_idtitleartist_idlength_sec
1718Last Tram7310
56Paper Moon2305
1819Iron Bridge7300

Same as sort then head, in one call.

Jobs Sort by two columns

Show the result without running
Result: DataFrame, 8 rows, 3 columns
offer_idlevelbase_salary
3940Junior52000.0
1718Junior48000.0
1819Junior48000.0
3839Junior45000.0
2324Junior44500.0
4142Junior44000.0
3435Junior43000.0
56Junior41500.0

Level A to Z, then salary high to low inside each level. Text sorts by letter, so Junior, Mid, Senior.

Football Where do blanks go?

Predict first: Where will the postponed matches end up?

Show the result without running
Result: DataFrame, 6 rows, 6 columns
match_idmatch_datehome_team_idaway_team_idhome_goalsaway_goals
19202024-09-14263.01.0
232024-08-03233.00.0
26272024-09-2863NaNNaN
27282024-10-0536NaNNaN
28292024-10-0513NaNNaN
29302024-10-0564NaNNaN

Blanks go last, whichever way you sort. Pass na_position="first" to move them.

Common mistake

Expecting sort_values to change the table. df.sort_values("price") gives back a sorted copy; on its own line it changes nothing. Store it or chain .head(). And say how you break ties, with a second sort column.

Try it yourself

  1. App The 5 earliest sign-ups: return user_id and signup_date, earliest first. Break ties by lower user_id.

    Hint

    Sort by ["signup_date", "user_id"], then head(5).

    Show the answer
  2. Shop The top 3 orders by quantity, biggest first. Break ties by lower order_id. Return order_id and quantity.

    Hint

    ascending=[False, True].

    Show the answer

After this step you can answer any "top 3" or "lowest 5" question and say how you broke ties.

Step 19Count values: value_counts, nunique, uniqueLevel 2

You know: Counter and picking a column. New: the pandas way to count.

value_counts counts each value, biggest first. nunique says how many different values there are.

df["col"].value_counts()                 # count of each value
df["col"].value_counts(normalize=True)   # shares that add up to 1
df["col"].value_counts(dropna=False)     # count blanks too
df["col"].nunique()                      # how many different values
df["col"].unique()                       # what they are

Examples

Shop Orders by status

Show the result without running
Result: Series, 3 rows
statuscount
delivered57
returned8
cancelled5

The same as Counter, as a Series.

Music Shares, not counts

Show the result without running
Result: Series, 2 rows
planproportion
free0.6
premium0.4

normalize=True divides by the total.

App Blanks are left out unless you ask

Predict first: Will users with no referrer be counted?

Show the result without running
Printed
29 users counted, out of 36
Result: Series, 4 rows
referrercount
ad13
search9
NaN7
friend7

Seven users have no referrer. Without dropna=False they vanish from the count.

Jobs Rows against different values

Show the result without running
Printed
45 offers
11 companies made them
Result
array(['Sales', 'Data', 'Product', 'Design', 'Engineering'], dtype=object)

len counts rows. nunique counts different values.

Common mistake

Trusting value_counts() to show blanks. It drops them by default, so the counts add up to less than the row count. Add dropna=False when blanks matter.

Try it yourself

  1. App Count users in each country. Return the counts with the country they belong to.

    Hint

    value_counts on the country column.

    Show the answer
  2. Music How many different listeners streamed at least once? Store the number in answer.

    Hint

    nunique on listener_id in streams.

    Show the answer

After this step you can count each value, get shares, and count distinct values.

Step 20Blanks: isna, fillna, dropnaLevel 2

You know: filtering and counting. New: finding and handling missing values, which pandas shows as NaN.

NaN means missing. Find it with .isna(). Fill with .fillna(). Drop with .dropna().

df.isna().sum()                      # blanks in each column
df[df["col"].isna()]                 # rows where col is blank
df["col"].fillna(0)                  # fill blanks
df.dropna(subset=["col"])            # drop rows with col blank

Examples

Shop Blanks in every column

Show the result without running
Result: Series, 5 rows
customer_id0
name0
city1
email2
signup_date0

The first thing to run on any new file.

Football Matches not played yet

Show the result without running
Result: DataFrame, 4 rows, 6 columns
match_idmatch_datehome_team_idaway_team_idhome_goalsaway_goals
26272024-09-2863NaNNaN
27282024-10-0536NaNNaN
28292024-10-0513NaNNaN
29302024-10-0564NaNNaN

No score yet is NaN, not 0.

Shop Fill or skip: two different averages

Predict first: Which average will be bigger?

Show the result without running
Printed
6.666666666666667
1.1428571428571428

mean skips blanks. Filling with 0 says "no discount", which changes the answer. Pick one and say why.

App Not equal keeps the blanks

Predict first: Will users with no referrer appear?

Show the result without running
Printed
23
Result: Series, 3 rows
referrercount
search9
NaN7
friend7

In pandas, a blank is "not equal to ad", so the 7 blanks stay in. In SQL, referrer <> 'ad' drops them. Same question, different answer.

Jobs Drop rows missing one column

Show the result without running
Printed
45
44
37

Plain dropna() drops a row if any column is blank. That throws away offers that only lack accepted_at.

Common mistake

df["col"] == None or == np.nan matches nothing, because NaN is not equal to anything, even itself. Use .isna().

Try it yourself

  1. Jobs Store a list of the offer_id values for offers never accepted (blank accepted_at).

    Hint

    Filter with .isna(), pick offer_id, then .tolist().

    Show the answer
  2. Music Return each listener's name and country, with a blank country shown as Unknown. Keep every listener.

    Hint

    fillna on the country column.

    Show the answer

After this step you can count blanks in every column, fill them or drop them, and say which you did.

Level 2 of 5 done. You can now load any CSV and answer one-table questions with pandas.

L3 Grouping and joining

groupby, several sums at once, merge, pivot tables and buckets.

Step 21groupby: one number per groupLevel 3

You know: value_counts and picking columns. New: splitting a table into groups and summing, averaging or counting each one.

groupby says what to group by. Then pick a column and finish with sum, mean, size and so on.

df.groupby("key")["value"].sum()
df.groupby("key", as_index=False)["value"].mean()   # key stays a column
df.groupby(["a", "b"]).size()                       # rows per pair

Examples

Shop Items bought by each customer

Show the result without running
Result: Series, 5 rows
customer_idquantity
511
311
19
108
27

The group key becomes the index of the result.

Jobs Average salary by family

Show the result without running
Result: DataFrame, 5 rows, 2 columns
job_familybase_salary
Data55727.0
Design54389.0
Engineering57125.0
Product56821.0
Sales35417.0

as_index=False keeps job_family as an ordinary column. Easier to merge or plot later.

Music Plays per song

Show the result without running
Result: Series, 3 rows
song_id
529
418
114

size counts rows in each group.

App Group by two columns

Show the result without running
Result: DataFrame, 11 rows, 3 columns
platformcountryusers
androidDE1
androidIE10
androidUK2
androidUS3
iosIE5
iosUK3
iosUS1
webDE6
webIE3
webUK1
webUS1

reset_index(name=...) turns the result back into a flat table with a named count.

Football Blanks are skipped in a sum

Predict first: Will the postponed matches cause an error?

Show the result without running
Result: Series, 6 rows
home_team_idhome_goals
17.0
212.0
36.0
47.0
54.0
62.0

Postponed matches add nothing. sum skips NaN.

Common mistake

Stopping at groupby. df.groupby("key") on its own shows <DataFrameGroupBy object>. Finish it with an aggregate. And count skips blanks while size does not.

Try it yourself

  1. Jobs Average base_salary for each level, rounded to 0 decimals. Return level and the average.

    Hint

    groupby level, pick base_salary, .mean().round(0).

    Show the answer
  2. Music Total seconds_played for each listener_id.

    Hint

    groupby listener_id, then sum.

    Show the answer

After this step you can answer "total per", "average per" and "how many per" questions.

Step 22Several numbers per group: named aggLevel 3

You know: groupby with one aggregate. New: many aggregates at once, with names you choose, then filtering the groups.

.agg(new_name=("column", "function")) gives flat, named columns.

summary = df.groupby("key").agg(
    total=("value", "sum"),
    average=("value", "mean"),
    n=("value", "size"),
).reset_index()
summary[summary["n"] >= 5]        # like HAVING in SQL

Examples

Shop A summary per customer

Show the result without running
Result: DataFrame, 5 rows, 4 columns
customer_idordersunitslast_order
1892025-06-04
2672025-04-28
37112025-05-14
4332025-06-14
56112025-06-24

max on YYYY-MM-DD text gives the latest date.

Music Count a condition per group

Show the result without running
Result: DataFrame, 5 rows, 2 columns
listener_idplaysskips
1170
281
3171
460
5120

Summing True and False counts the Trues.

Jobs Filter the groups afterwards

Show the result without running
Result: DataFrame, 3 rows, 2 columns
job_familynavg_salary
Data1155727.0
Design1054389.0
Product1456821.0

Filter rows before grouping (like WHERE), or groups after (like HAVING).

Football Several stats on a whole table

Show the result without running
Result: DataFrame, 3 rows, 2 columns
home_goalsaway_goals
sum38.034.0
mean1.46151.3077
max3.05.0

No groupby: one row per statistic.

Common mistake

.agg(["sum", "mean"]) after a groupby gives two-level column names that are awkward to use later. Named aggregation gives flat names you choose.

Try it yourself

  1. Jobs For each job_family with at least 10 offers: the number of offers (n) and the highest salary (top).

    Hint

    agg(n=..., top=...), then keep rows where n >= 10.

    Show the answer
  2. Shop For each customer_id: the number of orders and the first order date. Name the columns customer_id, n_orders, first_order.

    Hint

    agg(n_orders=("order_id", "count"), first_order=("order_date", "min")).reset_index()

    Show the answer

After this step you can build a summary table per group and keep only the groups that pass a test.

Step 23merge: join tables, and find what is missingLevel 3

You know: groupby and filtering. New: joining two tables on a shared column.

merge joins on a key. how="inner" keeps matches only; how="left" keeps every left row. indicator=True tells you which side each row came from.

a.merge(b, on="key")                          # inner: rows in both
a.merge(b, on="key", how="left")              # every row of a
a.merge(b, left_on="x_id", right_on="id")     # keys with different names
m = a.merge(b, on="key", how="left", indicator=True)
m[m["_merge"] == "left_only"]                 # in a, not in b

Examples

Shop Orders with product details

Show the result without running
Result: DataFrame, 5 rows, 5 columns
order_idnamequantitypriceline_total
1Trail Runner Shoes189.089.0
2Camping Stove245.591.0
3Puzzle 1000118.018.0
4Cookbook: Brown Bread124.024.0
5Atlas of Islands138.038.0

Each order picks up its product's name and price.

Music Three tables: plays per artist

Show the result without running
Result: Series, 7 rows
name
Mara Vale67
The Gannets28
Neon Curlew24
Low Kettle22
Driftwood Kids21
Brass Harbour4
Sally Gap4

Chain merges one after another, like JOIN after JOIN.

Football Keys with different names

Show the result without running
Result: DataFrame, 5 rows, 3 columns
match_idnamehome_goals
1Shannon Celtic0.0
2Riverside Rovers2.0
3Harbour United3.0
4Shannon Celtic1.0
5Harbour United2.0

left_on and right_on when the key column has a different name in each table.

Shop Customers who never ordered

Predict first: How many customers have never ordered?

Show the result without running
Result: DataFrame, 2 rows, 2 columns
customer_idname
7019Meabh Carroll
7120Lorcan Hayes

A left merge keeps everyone. left_only marks the rows with no order.

Jobs Check the row count

Show the result without running
Printed
45 45

Same count before and after: each offer found at most one company. validate raises an error if that is not true.

Common mistake

Merging on a key that repeats on both sides. Every match pairs up, so rows multiply and totals go up. Check len() before and after, or pass validate="many_to_one".

Hex and exams: In Hex you can join in a SQL cell or merge in a Python cell. Both give a dataframe. Pick one per project and stay with it, so a grader can follow the steps.

Try it yourself

  1. Shop Return the name of every customer who has never placed an order.

    Hint

    Left merge with indicator=True, keep left_only.

    Show the answer
  2. Music Plays per artist name, including any artist with 0 plays.

    Hint

    Start from artists and merge left twice. Count stream_id, which is blank where there was no play.

    Show the answer

After this step you can join two or three tables, check the row count, and list what has no match.

Step 24pivot_table and crosstabLevel 3

You know: groupby by two columns. New: spreading one of them across the top, like a spreadsheet pivot.

pivot_table puts one key down the side and one across the top. crosstab is the quick version for counts.

pd.pivot_table(df, index="row_key", columns="col_key",
               values="value", aggfunc="sum", fill_value=0)
pd.crosstab(df["a"], df["b"])                  # counts
pd.crosstab(df["a"], df["b"], margins=True)    # with totals

Examples

Shop Orders by month and status

Show the result without running
Result: DataFrame, 6 rows, 3 columns
monthcancelleddeliveredreturned
2025-011131
2025-02282
2025-03180
2025-041113
2025-05070
2025-060102

.str[:7] takes YYYY-MM from the date text. Proper dates come in Level 4.

Jobs Average salary by level and family

Show the result without running
Result: DataFrame, 3 rows, 5 columns
levelDataDesignEngineeringProductSales
Junior41000.037250.048000.043500.032000.0
Mid55750.046833.066250.056800.042250.0
Senior74125.068625.0NaN83500.0NaN

A blank cell means no offers for that pair.

Music Plays by country and plan

Show the result without running
Result: DataFrame, 4 rows, 2 columns
countryfreepremium
DE260
FR629
IE2717
UK461

fill_value=0 shows 0 where there were no plays.

App Counts with totals

Predict first: Will the All column add up to 36?

Show the result without running
Result: DataFrame, 4 rows, 4 columns
platformadfriendsearchAll
android55313
ios5139
web3137
All137929

margins=True adds an All row and column. The users with no referrer are left out of the grid.

Common mistake

Using pivot (no _table) when a row and column pair appears more than once. It fails with Index contains duplicate entries. pivot_table adds them up instead.

Try it yourself

  1. App Count users by platform (rows) and country (columns), with 0 where there are none.

    Hint

    pd.crosstab with platform first.

    Show the answer
  2. Jobs Count offers by level (rows) and status (columns).

    Hint

    pd.crosstab again.

    Show the answer

After this step you can build a grid of counts or averages with rows, columns and totals.

Step 25Buckets and labels: np.where, map, pd.cut, np.selectLevel 3

You know: if/elif/else, dictionaries and functions. New: doing the same on a whole column at once.

np.where is if/else for a column. np.select is if/elif/else. map looks codes up in a dictionary. pd.cut makes bands.

df["flag"] = np.where(df["x"] > 100, "high", "low")
df["label"] = np.select([cond1, cond2], ["a", "b"], default="other")
df["name"] = df["code"].map({"IE": "Ireland", "UK": "United Kingdom"})
df["band"] = pd.cut(df["x"], bins=[0, 20, 50, 1000], labels=["low", "mid", "high"])
df["y"] = df["x"].apply(my_function)

Examples

Music if/else on a column

Show the result without running
Result: Series, 2 rows
kindcount
play165
skip5

One line instead of a loop over 170 rows.

Shop Price bands with pd.cut

Show the result without running
Result: DataFrame, 12 rows, 3 columns
namepriceband
Trail Runner Shoes89.0over 50
Camping Stove45.520 to 50
Rain Jacket120.0over 50
Board Game: Harbour34.9920 to 50
Puzzle 100018.0under 20
Card Game: Gulls12.5under 20
Chef Knife59.0over 50
Cast Iron Pan42.020 to 50
Coffee Grinder75.0over 50
Novel: Low Tide14.99under 20
Cookbook: Brown Bread24.020 to 50
Atlas of Islands38.020 to 50

Each band includes its top edge: 20 goes in "under 20".

Football Three outcomes and a default

Predict first: What will the postponed matches get?

Show the result without running
Result: Series, 4 rows
resultcount
H13
A8
D5
not played4

A blank fails every test, so postponed matches fall to the default.

App Map codes to names

Show the result without running
Result: DataFrame, 5 rows, 3 columns
user_idcountrycountry_name
3132UKUnited Kingdom
3233IEIreland
3334IEIreland
3435IEIreland
3536IEIreland

A code missing from the dictionary becomes NaN. US is not in it.

Jobs Your own function with apply

Show the result without running
Result: Series, 3 rows
bandcount
under 60k30
60k plus14
unknown1

apply runs your function on every value. Slower than np.where, but fine for small tables and clear to read.

Common mistake

Forgetting which edge pd.cut includes. By default a band is (20, 50]: 20 is out, 50 is in. Pass right=False to make it [20, 50), and check a value that sits on an edge.

Try it yourself

  1. Football Add a result column: H, A, D, or P for a postponed match. Return match_id and result.

    Hint

    np.select with three tests and default="P".

    Show the answer
  2. Jobs Band salaries: under 40,000 is low, 40,000 up to under 60,000 is mid, 60,000 and over is high. Count the offers in each band. Leave out the blank salary.

    Hint

    pd.cut with right=False, then value_counts. Watch the offer at exactly 40,000.

    Show the answer

After this step you can label rows by a rule, map codes to names and put numbers into bands.

Level 3 of 5 done. You can now answer most take-home questions: totals by group, joins, and what is missing.

L4 Dates and order

Dates, change on last month, running totals, ranks, duplicates.

Step 26Dates: parse, take parts, count by monthLevel 4

You know: columns, groupby and text slices. New: real dates, so you can take the month, the weekday or the days between two dates.

pd.to_datetime turns text into dates. Then .dt gives the parts. to_period("M") and resample group by month.

df["d"] = pd.to_datetime(df["d"])
df["d"].dt.year, df["d"].dt.month, df["d"].dt.day_name()
df["month"] = df["d"].dt.to_period("M")        # 2025-03
(df["end"] - df["start"]).dt.days               # days between
df.groupby(df["d"].dt.to_period("M")).size()    # count by month
df.set_index("d").resample("MS")["x"].sum()     # the same with resample

Examples

Music Plays by weekday

Show the result without running
Result: Series, 7 rows
weekdaycount
Thursday28
Friday26
Tuesday24
Wednesday24
Saturday23
Sunday23
Monday22

.dt only works once the column is a real date.

Shop Orders per month

Show the result without running
Result: Series, 6 rows
order_date
2025-0115
2025-0212
2025-039
2025-0415
2025-057
2025-0612

parse_dates converts while reading. A Period like 2025-03 is a whole month.

Jobs Days between two dates

Show the result without running
Result: DataFrame, 5 rows, 4 columns
offer_idoffered_ataccepted_atdays_to_accept
12023-01-052023-01-138.0
22023-01-122023-01-2513.0
32023-01-16NaTNaN
42023-01-312023-02-1313.0
52023-02-062023-02-104.0

Subtracting dates gives a gap. .dt.days turns it into a number. A blank date gives a blank gap.

App resample by month

Show the result without running
Result: Series, 3 rows
signup_dateuser_id
2025-01-0112
2025-02-0112
2025-03-0112

resample needs the date as the index. "MS" labels each month by its first day.

Football Filter on a date part

Show the result without running
Printed
12 matches in September
Result: DataFrame, 5 rows, 2 columns
match_idmatch_date
15162024-09-07
16172024-09-07
17182024-09-07
18192024-09-14
19202024-09-14

Month 9 in any year. Add .dt.year == 2024 if the data spans years.

Common mistake

Using .dt on text. Dates read from a CSV are text until you convert them, so .dt.month gives AttributeError: Can only use .dt accessor with datetimelike values. Run pd.to_datetime first, or pass parse_dates to read_csv.

Hex and exams: If the data comes from a SQL cell, the date columns usually arrive as real dates already. Check with df.dtypes before converting.

Try it yourself

  1. Shop Count orders per month, with the month shown as YYYY-MM.

    Hint

    to_datetime, then groupby on .dt.to_period("M"), then size().

    Show the answer
  2. Jobs Average number of days from offered_at to accepted_at, for accepted offers, rounded to 1 decimal.

    Hint

    Subtract, .dt.days, .mean(), round. Blanks are skipped by mean.

    Show the answer

After this step you can turn text into dates, count by month or weekday, and work out days between events.

Step 27Change on the last period: shift, diff, pct_changeLevel 4

You know: dates and groupby by month. New: comparing each row with the one before it.

shift(1) moves a column down one row, so each row can see the previous one. diff and pct_change do the sum for you.

m = df.groupby("month")["x"].sum().reset_index()
m["prev"] = m["x"].shift(1)
m["change"] = m["x"].diff()
m["pct"] = (m["x"].pct_change() * 100).round(1)
df["prev_in_group"] = df.groupby("key")["x"].shift(1)

Examples

Shop Orders per month, against the month before

Show the result without running
Result: DataFrame, 6 rows, 5 columns
monthordersprevchangepct
2025-0115NaNNaNNaN
2025-021215.0-3.0-20.0
2025-03912.0-3.0-25.0
2025-04159.06.066.7
2025-05715.0-8.0-53.3
2025-06127.05.071.4

The first month has no month before it, so it gets NaN.

Music Day-on-day change

Show the result without running
Result: Series, 7 rows
streamed_on
2025-03-01NaN
2025-03-02-2.0
2025-03-031.0
2025-03-042.0
2025-03-05-4.0
2025-03-063.0
2025-03-07-2.0

groupby sorts the dates, so each row really is the day before.

Jobs Year on year

Show the result without running
Printed
offered_at
2023    52960.0
2024    53421.0
Name: base_salary, dtype: float64
Result: Series, 2 rows
offered_atbase_salary
2023NaN
20240.9

pct_change is (this - last) / last.

App Time since the previous event, per user

Predict first: What will hours_since be on each user's first event?

Show the result without running
Result: DataFrame, 8 rows, 4 columns
user_idevent_nameevent_timehours_since
191signup2025-01-16 09:11:00NaN
201onboarding_done2025-01-16 11:54:002.7
211first_post2025-01-17 15:55:0028.0
301session_start2025-01-21 20:18:00100.4
531session_start2025-02-06 20:14:00383.9
1281session_start2025-03-20 08:38:00996.4
62signup2025-01-07 09:52:00NaN
72onboarding_done2025-01-07 11:19:001.4

groupby then shift looks back only within the same user. Each user's first event gets NaN.

Common mistake

Shifting an unsorted table. shift uses the row order, so if the months are not in order, "previous" is just whatever row came before. Sort by date first, and use groupby(...).shift() when there are groups.

Try it yourself

  1. Shop Which month had the biggest drop in order count against the month before? Return one row with month (YYYY-MM) and change (a negative number).

    Hint

    Monthly counts, .diff(), then nsmallest(1, "change").

    Show the answer
  2. Music Daily plays and the change from the day before. Return streamed_on, plays and change, one row per day (the first day's change is NaN).

    Hint

    groupby("streamed_on").size().reset_index(name="plays"), then .diff().

    Show the answer

After this step you can show month-on-month change, in numbers and in per cent, overall or per group.

Step 28Running totals and rolling averagesLevel 4

You know: shift and sorting by date. New: adding up as you go, and averaging over a moving window.

cumsum adds up as it goes. rolling(n).mean() averages the last n rows.

df["running"] = df["x"].cumsum()
df["running_in_group"] = df.groupby("key")["x"].cumsum()
df["nth_in_group"] = df.groupby("key").cumcount() + 1
df["avg_7"] = df["x"].rolling(7).mean()

Examples

Shop Orders so far, month by month

Show the result without running
Result: DataFrame, 6 rows, 3 columns
order_dateordersso_far
2025-011515
2025-021227
2025-03936
2025-041551
2025-05758
2025-061270

The last row of so_far equals the total row count.

Music A 7-day average

Predict first: Which is the first row with a number in avg_7?

Show the result without running
Result: DataFrame, 9 rows, 3 columns
streamed_onplaysavg_7
2025-03-017NaN
2025-03-025NaN
2025-03-036NaN
2025-03-048NaN
2025-03-054NaN
2025-03-067NaN
2025-03-0756.0
2025-03-0865.9
2025-03-0955.9

The first six days have no full week behind them, so they are NaN.

Jobs Number each offer within its family

Show the result without running
Result: DataFrame, 8 rows, 4 columns
offer_idjob_familyoffered_atnth_in_family
01Sales2023-01-051
12Data2023-01-121
23Product2023-01-161
34Product2023-01-312
45Data2023-02-062
56Data2023-02-233
67Design2023-03-121
78Design2023-03-152

cumcount starts at 0, so add 1.

Football Goals so far, round by round

Show the result without running
Result: DataFrame, 10 rows, 2 columns
match_dategoalsso_far
2024-08-039.09.0
2024-08-108.017.0
2024-08-177.024.0
2024-08-246.030.0
2024-08-316.036.0
2024-09-0712.048.0
2024-09-1412.060.0
2024-09-216.066.0
2024-09-286.072.0
2024-10-050.072.0

Rounds with postponed matches still add the goals that were scored.

Common mistake

Reading the first rows of a rolling average as real values. rolling(7) leaves the first six rows NaN. If a part-week average is fine, use rolling(7, min_periods=1), and say so in a comment.

Try it yourself

  1. App Sign-ups per signup_date and a running total. Return signup_date, signups and running, earliest date first.

    Hint

    groupby("signup_date").size().reset_index(name="signups"), then cumsum.

    Show the answer
  2. Music Daily plays and a 3-day rolling average, rounded to 1 decimal. Return streamed_on, plays and avg_3. The first two days stay NaN.

    Hint

    rolling(3).mean().round(1)

    Show the answer

After this step you can show a running total, a running count within groups, and a 7-day average.

Step 29Rank within a group, and the top N per groupLevel 4

You know: sorting, groupby and ties. New: ranking inside each group and keeping the top rows of each.

Sort, then groupby(...).head(n) keeps the top n of each group. groupby(...).rank() numbers them.

df.sort_values("x", ascending=False).groupby("key").head(3)
df["rank"] = df.groupby("key")["x"].rank(method="dense", ascending=False)

Examples

Shop How ties are ranked

Predict first: With dense, what rank does 59.0 get?

Show the result without running
Result: DataFrame, 4 rows, 4 columns
pricemindensefirst
120.01.01.01.0
89.02.02.02.0
89.02.02.03.0
59.04.03.04.0

min: 1, 2, 2, 4. dense: 1, 2, 2, 3. first: no ties, first seen wins. The default, average, gives 2.5 to both, which is rarely what an exam wants.

Jobs Top 2 salaries in each family

Show the result without running
Result: DataFrame, 10 rows, 3 columns
job_familyoffer_idbase_salary
25Data2683000.0
43Data4475000.0
42Design4374000.0
40Design4168500.0
14Engineering1569000.0
29Engineering3063500.0
44Product4592000.0
22Product2385000.0
8Sales942500.0
37Sales3842000.0

Sort once, then head(2) inside each group. The offer_id in the sort breaks ties.

Music Rank songs within each artist

Show the result without running
Result: DataFrame, 8 rows, 4 columns
artist_idtitleplaysrank_in_artist
01Salt Road141.0
11Kite Weather82.0
21Half Light63.0
42Glass Tide291.0
32Ferry Home182.0
52Paper Moon123.0
62Long Grass84.0
73Copper Sky141.0

rank gives floats like 1.0. Add .astype(int) if you want whole numbers.

Football Each team's best home score

Show the result without running
Result: DataFrame, 6 rows, 3 columns
home_team_idmatch_datehome_goals
112024-08-032.0
222024-08-033.0
932024-08-242.0
1842024-09-143.0
2552024-09-282.0
662024-08-171.0

head(1) is the top row per group. Earliest date wins a tie.

Common mistake

Leaving ties to chance. Sorting on one column and taking head(1) picks whichever tied row pandas met first. Add a second sort column that settles ties, and say which way you chose.

Try it yourself

  1. Jobs The highest-paid offer in each industry, with the company name. Ties: lower offer_id. Return industry, name, base_salary.

    Hint

    Merge offers with companies, sort by salary down and offer_id up, groupby("industry").head(1).

    Show the answer
  2. Music Each listener's most-streamed song. Ties: lower song_id. Return listener_id and song_id.

    Hint

    Count plays per listener and song, sort by plays down and song_id up, then groupby listener head(1).

    Show the answer

After this step you can answer "top 2 per family" or "best per listener" and choose how ties rank.

Step 30Duplicates, and the latest row per groupLevel 4

You know: sorting and top N per group. New: finding repeated rows, and keeping one row per key.

duplicated flags repeats. drop_duplicates removes them. Sort by date, then groupby(...).tail(1) keeps the latest per group.

df.duplicated(subset=["a", "b"]).sum()          # how many repeats
df.drop_duplicates(subset=["a", "b"], keep="first")
df.sort_values("date").groupby("key").tail(1)    # latest per key
df.loc[df.groupby("key")["date"].idxmax()]       # the same idea

Examples

Shop Find a double-submitted order

Show the result without running
Result: DataFrame, 2 rows, 7 columns
order_idcustomer_idproduct_idquantityorder_datestatusdiscount
40415522025-04-08deliveredNaN
69705522025-04-08deliveredNaN

keep=False flags every copy, so you see both rows.

App Rows before and after

Show the result without running
Printed
187 rows before
186 rows after

One event was logged twice. Say in a comment that you removed it.

Jobs Plain drop_duplicates misses it

Predict first: Will the first line drop the duplicate?

Show the result without running
Printed
45
44

Offers 18 and 19 differ only in offer_id, so they are not exact copies.

Music Each listener's latest stream

Show the result without running
Result: DataFrame, 14 rows, 5 columns
stream_idlistener_idsong_idstreamed_onseconds_played
140141152025-03-24186
162163252025-03-2880
154155352025-03-26154
163164452025-03-28249
1591605192025-03-27300
167168612025-03-28160
144145792025-03-24153
1611628122025-03-2714
1341359122025-03-22101
15615711142025-03-26207
1691701222025-03-28201
1461471342025-03-24192
15715814102025-03-2695
1311321512025-03-21265

Sort oldest to newest; tail(1) keeps the last row of each group.

Football idxmax: the row where the biggest value is

Show the result without running
Result: DataFrame, 6 rows, 3 columns
home_team_idmatch_idmatch_date
281292024-10-05
192202024-09-14
273282024-10-05
224232024-09-21
255262024-09-28
296302024-10-05

idxmax gives the row label of the max in each group. .loc pulls those rows. With ties it takes the first.

Common mistake

drop_duplicates() with no subset only drops rows that match in every column, including the id. A double-submitted order has a new id, so it survives. Name the columns that make two rows the same.

Try it yourself

  1. Jobs How many offers are left after removing duplicates? A duplicate matches in every column except offer_id. Store the number.

    Hint

    drop_duplicates(subset=every column but offer_id), then len.

    Show the answer
  2. Shop Each customer's most recent order. Ties on date: higher order_id. Return customer_id, order_id, order_date.

    Hint

    sort_values(["order_date", "order_id"]), groupby("customer_id").tail(1).

    Show the answer

After this step you can find and remove duplicates, and keep each customer's or user's latest record.

Level 4 of 5 done. You can now handle anything with time in it and pick the latest or top row per group.

L5 JSON and exam tasks

Nested JSON, funnels, clean functions with checks, and a chart with a headline.

Step 31JSON: nested dictionaries and listsLevel 5

You know: dictionaries, lists and loops. New: reading JSON, which is how most APIs send data.

json.load reads a file into dictionaries and lists. Then you walk down with keys and positions.

import json
with open("file.json") as f:
    data = json.load(f)          # from a file
data = json.loads(text)          # from a string
data.keys()                      # what is at the top
data["results"][0]["company"]["name"]
for r in data["results"]:
    print(r.get("salary", {}).get("base"))

Examples

Jobs Look at the top, then go down

Show the result without running
Printed
dict_keys(['page', 'count', 'results'])
8 results
Result
{'offer_id': 2,
 'company': {'name': 'Willowby Insurance', 'city': 'Galway'},
 'role': {'family': 'Data', 'level': 'Junior'},
 'salary': {'base': 37000, 'currency': 'EUR'},
 'perks': ['pension', 'remote']}

Print the keys first. Then look at one record before you write a loop.

Shop A total for each order

Show the result without running
Printed
101 Aoife Byrne 50.99
102 Ciara Brennan 120.0
103 Cian Walsh 176.0
104 Tadhg Burke 37.5
105 Niamh Kelly 107.0
106 Aoife Byrne 48.0

Each order holds a list of items. Loop inside a loop.

Football Skip what has no value yet

Show the result without running
Printed
2024-08-03 Shannon Celtic 0 - 2 Bogside Athletic
2024-08-03 Riverside Rovers 2 - 2 Claddagh Town
2024-08-03 Harbour United 3 - 0 Northside Wanderers
2024-08-04 Claddagh Town v Shannon Celtic not played

JSON null becomes Python None.

App Keys that are sometimes missing

Predict first: What will user 2's signup show as its platform?

Show the result without running
Printed
3 signup web
3 session_start web
4 signup web
4 onboarding_done web
2 signup unknown
2 first_post android
8 signup ios
8 subscribe ios

.get(key, {}) gives an empty dictionary when props is missing, so the second .get still works.

Common mistake

Mixing up json.load and json.loads. load reads an open file; loads reads a string (the s is for string). And JSON uses true, false and null, which arrive as True, False and None.

Try it yourself

  1. Shop From orders_api.json, store the total value of every item in every order (qty times price), rounded to 2 decimals.

    Hint

    Two loops, or one sum over a generator with two fors.

    Show the answer
  2. Jobs From offers_api.json, store a list of the company names for offers whose perks include remote, in file order.

    Hint

    Loop over data["results"], test "remote" in r["perks"].

    Show the answer

After this step you can open a JSON file, find your way down to the value you want, and loop over records safely.

Step 32JSON to a table: json_normalize and explodeLevel 5

You know: JSON and DataFrames. New: flattening nested JSON into a table, and turning a list in a cell into rows.

pd.json_normalize turns nested keys into columns. record_path makes one row per item in a list. explode does the same for a list column.

pd.json_normalize(records)                                   # company.name and so on
pd.json_normalize(data, record_path="items", meta=["order_id"])   # one row per item
df.explode("list_col")                                       # one row per list item

Examples

Jobs Nested keys become columns

Show the result without running
Result: DataFrame, 8 rows, 8 columns
offer_idperkscompany.namecompany.cityrole.familyrole.levelsalary.basesalary.currency
2['pension', 'remote']Willowby InsuranceGalwayDataJunior37000EUR
3['pension', 'bonus']Umberfield SoftwareLondonProductMid61000EUR
4[]Quillstone MediaLondonProductMid53500EUR
7['remote', 'bonus', 'pension']Brightwell AnalyticsDublinDataSenior78000EUR
9['car']Larkspur FreightNoneSalesJunior34000EUR
12['remote']Pixelmoor GamesDublinDesignMid52000EUR
15['pension', 'bonus']Kettlebrook BankDublinEngineeringSenior82000EUR
20['remote', 'pension']Brightwell AnalyticsDublinDesignJunior38000EUR

Nested names are joined with dots: company.name, salary.base.

Shop One row per item

Show the result without running
Result: DataFrame, 10 rows, 6 columns
skunameqtypriceorder_idcustomer.name
P05Puzzle 1000218.0101Aoife Byrne
P10Novel: Low Tide114.99101Aoife Byrne
P03Rain Jacket1120.0102Ciara Brennan
P07Chef Knife159.0103Cian Walsh
P08Cast Iron Pan142.0103Cian Walsh
P09Coffee Grinder175.0103Cian Walsh
P06Card Game: Gulls312.5104Tadhg Burke
P01Trail Runner Shoes189.0105Niamh Kelly
P05Puzzle 1000118.0105Niamh Kelly
P11Cookbook: Brown Bread224.0106Aoife Byrne

meta copies fields from the parent order onto each item row.

Music explode a list column

Predict first: What happens to Cara's empty playlist?

Show the result without running
Printed
7 playlists
Result: DataFrame, 17 rows, 3 columns
namesongslistener
0MorningSalt RoadAda
0MorningHalf LightAda
0MorningWren SongAda
1RunGlass TideAda
1RunStatic BloomAda
2CommuteNight BusBen
2CommuteLast TramBen
2CommuteSalt RoadBen
3FocusSoft FocusCara
3FocusBlue HourCara
3FocusHalf LightCara
4SundaySlow RainCara
5EmptyNaNCara
6MixGlass TideDev
6MixSalt RoadDev
6MixIron BridgeDev
6MixHalf LightDev

Each song in a playlist gets its own row. An empty list becomes one row with NaN.

App Missing keys become NaN

Show the result without running
Result: DataFrame, 8 rows, 6 columns
user_ideventtimeprops.platformprops.screenprops.plan
3signup2025-01-01T09:54:00webwelcomeNaN
3session_start2025-01-03T11:42:00webNaNNaN
4signup2025-01-03T09:18:00webwelcomeNaN
4onboarding_done2025-01-03T11:20:00webprofileNaN
2signup2025-01-07T14:02:00NaNNaNNaN
2first_post2025-01-08T19:30:00androideditorNaN
8signup2025-01-09T10:15:00ioswelcomeNaN
8subscribe2025-01-20T08:05:00iosplansyearly

Records without props, or without props.screen, get NaN in those columns.

Common mistake

Using dot access on dotted column names. df.company.name fails; the column is called "company.name". Write df["company.name"], or pass sep="_" to get company_name.

Try it yourself

  1. Shop One row per item from orders_api.json, with order_id, name and line_total (qty times price).

    Hint

    json_normalize with record_path="items" and meta=["order_id"].

    Show the answer
  2. Music How many times does each song appear across all playlists? Return each song with its count.

    Hint

    json_normalize with record_path, explode("songs"), then value_counts.

    Show the answer

After this step you can take an API response to a flat DataFrame and carry on with everything from Levels 2 to 4.

Step 33Funnels and retentionLevel 5

You know: nunique, merge and dates. New: putting them together to answer "how many made it to the next step".

Count users, not rows, at each step. Divide by the step before, or by the first step, and say which.

steps = ["signup", "onboarding_done", "first_post", "subscribe"]
users = [events.loc[events["event_name"] == s, "user_id"].nunique() for s in steps]
funnel = pd.DataFrame({"step": steps, "users": users})
funnel["pct_of_start"] = (100 * funnel["users"] / funnel["users"].iloc[0]).round(1)
funnel["pct_of_prev"] = (100 * funnel["users"] / funnel["users"].shift(1)).round(1)

Examples

App A four-step funnel

Show the result without running
Result: DataFrame, 4 rows, 4 columns
stepuserspct_of_startpct_of_prev
signup36100.0NaN
onboarding_done3083.383.3
first_post1747.256.7
subscribe1027.858.8

Two percentages answer two questions. Label which one you report.

Shop Repeat customers

Show the result without running
Printed
18 customers ordered
16 ordered more than once
Result
88.9

The mean of True and False is the share that are True.

App Conversion by sign-up month

Show the result without running
Result: DataFrame, 3 rows, 3 columns
monthsumcountmean
2025-012120.17
2025-022120.17
2025-036120.5

A cohort is a group that started at the same time. Compare cohorts, not totals.

Music Who came back in week 4?

Predict first: Is week-4 retention above or below 50%?

Show the result without running
Printed
12 listened in week 1
11 of them came back in week 4
Result
91.7

& on two sets keeps what is in both. Day 1 to 7 is week 1, and so on.

Common mistake

Counting events instead of users. events["event_name"].value_counts() counts rows, so one user with five sessions counts five times. Use nunique() on user_id for each step.

Try it yourself

  1. App Of users who finished onboarding, what percentage made a first post? Store one number, rounded to 1 decimal.

    Hint

    Two sets of user_ids: onboarding_done and first_post. Both, divided by onboarding.

    Show the answer
  2. Shop Of customers who ordered at least once, what percentage ordered more than once? Store one number, rounded to 1 decimal.

    Hint

    groupby customer_id size, then the share that is 2 or more.

    Show the answer

After this step you can build a funnel, a repeat rate and a simple retention table.

Step 34A clean function with sanity checksLevel 5

You know: functions, merge and groupby. New: wrapping a whole answer in one function, with asserts that stop it if something is off.

One function, one job, a docstring, and assert lines for the things that must be true.

def monthly_revenue(orders, products, status="delivered"):
    """Revenue per month for orders with this status."""
    df = orders.merge(products, on="product_id", how="left")
    assert len(df) == len(orders), "merge changed the row count"
    ...
    return result

result = monthly_revenue(orders, products)
assert result["revenue"].ge(0).all(), "negative revenue"

Examples

Shop A function you can rerun

Show the result without running
Result: DataFrame, 6 rows, 2 columns
monthrevenue
2025-01613.99
2025-02320.99
2025-03418.43
2025-04991.0
2025-05899.5
2025-06490.47

Each assert states a fact the answer depends on. If one fails, you find out now, not from the grader.

App An assert that catches a problem

Predict first: Will this pass?

Show the result without running
Result
Line 3: AssertionError: 1 duplicate event rows

It fails, on purpose. The message says what is wrong. Fix the data, then the check passes.

Jobs Test the function on more than one input

Show the result without running
Printed
Junior 40000.0
Mid 54000.0
Senior 74000.0

The last assert is a sense check: if Juniors earn more than Seniors, something upstream is wrong.

Football Check a total two ways

Show the result without running
Result
{'H': 13, 'D': 5, 'A': 8}

Every played match is exactly one of H, D or A. If the counts do not add up, a test is wrong.

Common mistake

Brackets round an assert. assert (x == y, "message") always passes, because a pair with something in it counts as True. Write assert x == y, "message" with no brackets round the whole thing.

Hex and exams: Before you hand in a notebook, restart it and run every cell from the top. That proves it does not depend on a cell you deleted or ran out of order.

Try it yourself

  1. Football Write points_table(matches) that returns each team_id and its points (3 for a win, 1 for a draw) from played matches, counting home and away games. Store points_table(matches) in answer.

    Hint

    Build one table of home results and one of away results with the same columns, pd.concat them, then groupby team_id and sum.

    Show the answer
  2. Jobs Write offers_per_company(offers, companies) that returns every company name with its number of offers n, after removing duplicate offers (same in every column but offer_id). Store the result for the two files in answer.

    Hint

    drop_duplicates with a subset, merge with companies, groupby name, size.

    Show the answer

After this step you can hand in an answer a grader can rerun, with checks that prove the numbers add up.

Step 35A quick chart with a headline titleLevel 5

You know: groupby and f-strings. New: matplotlib, and a title that says what the chart shows.

Build the small table first. Then plot it, and make the title the finding, not the topic.

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.bar(df["label"], df["value"], color="#3E86B5")
ax.set_title(f"{top_label} had the most")      # the finding
ax.set_ylabel("Units")
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Examples

Shop Bar chart with a title from the data

Show the result without runningChart drawn by the code above

The title is worked out from the data, so it stays true if the data changes. One bar in a darker colour points the eye.

Music A line with a rolling average

Show the result without runningChart drawn by the code above

Plot the noisy line light and the smooth one dark.

Jobs Horizontal bars, sorted

Show the result without runningChart drawn by the code above

Sorted bars read top to bottom. Long labels fit better on a horizontal chart.

App A funnel as bars

Show the result without runningChart drawn by the code above

Labels on the bars save the reader from reading the axis.

Common mistake

A title that names the topic, like "Revenue by month". It makes the reader do the work. Say the finding, like "May was the best month", and work it out from the data so it stays true.

Hex and exams: Hex has its own chart cells as well as matplotlib in Python cells. Either is fine in a take-home. What graders look for is the same: a clear title, labelled axes, and one point per chart.

Try it yourself

  1. Jobs Before you plot, write the headline. Store the text Product had the most offers (14), but worked out from the data, in answer.

    Hint

    value_counts(), then .index[0] and .iloc[0] in an f-string.

    Show the answer
  2. Music Build the table you would plot: plays per genre, highest first. Return genre and plays.

    Hint

    Merge streams, songs and artists; groupby genre; size; sort descending.

    Show the answer

After this step you can draw a bar or line chart in a few lines, with a title worked out from the data.

Level 5 of 5 done. You can now take a messy file to a checked answer and a chart someone can read in five seconds.

▸ Pure Python or pandas?

Many timed coding tests ban pandas, or only give you the standard library. Take-home tasks and notebooks like Hex expect pandas. Practise both. The same job, both ways:

JobPure Pythonpandas
Read a CSVlist(csv.DictReader(f))pd.read_csv("f.csv")
Keep some rows[r for r in rows if r["x"] == "a"]df[df["x"] == "a"]
Count each valueCounter(r["x"] for r in rows)df["x"].value_counts()
Total per groupd[k] = d.get(k, 0) + v in a loopdf.groupby("k")["v"].sum()
Top 3sorted(rows, key=..., reverse=True)[:3]df.nlargest(3, "v")
Join two tablesbuild a lookup dictionary, then loopa.merge(b, on="k")
Blanksempty text "" from csv, None from JSONNaN; use .isna()
Numberstext until you call int() or float()converted for you when the column is clean

Read the rules before you start. If they say "standard library only", csv, json, collections and datetime are usually allowed. Steps 7 to 14 and mock question 7 practise exactly that.

▸ Hex on exam day

▸ Mock exam: 10 questions

Give yourself 60 minutes. No AI, and no hints until you have had a real go. Each question mixes two or three steps, like a real exam. Question 7 bans pandas.

0 of 10 correct so far
  1. Shop Which month had the highest delivered revenue (quantity times price)? Return one row: month (YYYY-MM) and revenue rounded to 2 decimals.

    Hint

    Filter delivered, merge products, groupby month, sum, nlargest(1).

    Show the answer
  2. Music Each listener's favourite artist: the one they streamed most. Ties: lower artist_id. Return listener_id and artist_id.

    Hint

    Merge streams with songs, count per listener and artist, sort, groupby head(1).

    Show the answer
  3. Football Which team has the most points (3 for a win, 1 for a draw) from played matches, home and away? Return one row: name and points.

    Hint

    Stack home and away results with pd.concat, as in step 34, then merge team names.

    Show the answer
  4. App Of users who signed up, what percentage subscribed? Store one number, rounded to 1 decimal.

    Hint

    nunique users with subscribe over nunique users with signup.

    Show the answer
  5. Jobs Acceptance rate by company: accepted offers as a percentage of all offers, rounded to 1 decimal, for companies with at least 3 offers. Return name and accept_pct.

    Hint

    Merge companies, groupby name with agg(n=..., accepted=...), filter n >= 3, then divide.

    Show the answer
  6. Music Skip rate (plays under 30 seconds) for each plan, as a percentage rounded to 1 decimal. Return plan and skip_pct.

    Hint

    Merge listeners, flag skips, groupby plan, mean of the flag times 100.

    Show the answer
  7. Shop No pandas allowed. Using csv only, store a dictionary of product category to total units (quantity) in delivered orders.

    Hint

    Read products.csv into a dict of product_id to category first. Then loop over orders, skipping any status that is not delivered.

    Show the answer
  8. Jobs From offers_api.json, store a dictionary of level to average base salary, rounded to 0 decimals.

    Hint

    json_normalize, then groupby("role.level")["salary.base"].mean().round(0), then .to_dict().

    Show the answer
  9. App For each platform, the median hours from a user's signup event to their onboarding_done event, for users who finished onboarding, rounded to 1 decimal.

    Hint

    Two filtered tables, one per event, merged on user_id. Then merge app_users for platform.

    Show the answer
  10. Jobs Remove duplicate offers (same in every column but offer_id), then give the average base salary per industry, rounded to 0 decimals.

    Hint

    drop_duplicates with a subset, merge companies, groupby industry.

    Show the answer

▸ Practice next