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
- 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.
- Predict. Before you press Run, guess what comes back.
- Run it, then change it. Every box is editable. Reset puts it back. Most examples suggest one thing to change.
- 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.
- 1Run your first line
- 2Name a value: variables
- 3Numbers and text are different
- 4Maths: + - * / // % and round
- 5A first list
- 6A first loop
1Core Python for exams
Decisions, lists, text, dictionaries, functions, counting and sorting. No libraries.
- 7Decisions: if, elif, else
- 8Lists in depth: append, slices, in, sorted, set
- 9Text: string methods and f-strings
- 10Dictionaries: look things up by name
- 11Functions: write a step once, use it many times
- 12Comprehensions: a loop in one line
- 13Counting: a dictionary, Counter, and CSV without pandas
- 14Sorting with a key, and ties
2pandas basics
Read a CSV, look at it, pick columns, filter, sort, count, handle blanks.
- 15Read a CSV and take a first look
- 16Columns: pick, make and rename
- 17Filter rows: masks, &, |, isin, between
- 18Sort, and the top N
- 19Count values: value_counts, nunique, unique
- 20Blanks: isna, fillna, dropna
3Grouping and joining
groupby, several sums at once, merge, pivot tables and buckets.
- 21groupby: one number per group
- 22Several numbers per group: named agg
- 23merge: join tables, and find what is missing
- 24pivot_table and crosstab
- 25Buckets and labels: np.where, map, pd.cut, np.select
4Dates and order
Dates, change on last month, running totals, ranks, duplicates.
- 26Dates: parse, take parts, count by month
- 27Change on the last period: shift, diff, pct_change
- 28Running totals and rolling averages
- 29Rank within a group, and the top N per group
- 30Duplicates, and the latest row per group
5JSON and exam tasks
Nested JSON, funnels, clean functions with checks, and a chart with a headline.
- 31JSON: nested dictionaries and lists
- 32JSON to a table: json_normalize and explode
- 33Funnels and retention
- 34A clean function with sanity checks
- 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.
- Shop
customers.csv
20 customers. Two never ordered. Some have no city or email. - Shop
products.csv
12 products in 4 categories. - Shop
orders.csv
70 orders, Jan to Jun 2025. One was submitted twice. - Shop
orders_api.json
6 orders as an API would send them, with nested customers and item lists. - Music
listeners.csv
15 listeners, free or premium. - Music
artists.csv
8 artists. - Music
songs.csv
20 songs. One has never been played. - Music
streams.csv
170 plays, 1 to 28 March 2025. Under 30 seconds is a skip. - Music
playlists.json
4 listeners' playlists, each a list of songs. - Football
teams.csv
6 teams. - Football
matches.csv
30 fixtures. Four are postponed, with blank goals. - Football
fixtures.json
One round, nested home and away. - App
app_users.csv
36 users, Jan to Mar 2025. Seven have no referrer. - App
events.csv
signup, onboarding_done, first_post, subscribe, session_start. One row is logged twice. - App
app_events.json
8 events. Some have no props, some have extra keys. - Jobs
companies.csv
12 companies. - Jobs
offers.csv
45 offers. One salary is blank. Offers 18 and 19 are duplicates. - Jobs
employees.csv
30 employees. - Jobs
offers_api.json
8 offers from a made-up jobs API.
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)Slower version: Python from zero, 2.1 Values, variables and print
Examples
Shop Say hello
Show the result without running
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
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
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
This line is printed
'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
Music Every Try it yourself ends with a line that starts
answer =. Check looks at that value. Here, change the song afteranswer =toSalt Road, then press Check.Hint
Keep the quotes. Capital S and capital R.
Show the answer
Shop Make
answerhold 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)
Slower version: Python from zero, 2.1 Values, variables and print
Examples
Shop Price times quantity
Show the result without running
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
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
39000
The right side is worked out first, then stored back under the same name.
App Clear names help
Show the result without running
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
Football The home team scored 2 and the away team scored 1. Make
answerthe total goals, using the two names.Hint
Add the two names together.
Show the answer
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 numberSlower version: Python from zero, 2.2 Numbers and maths
Examples
Shop Four types
Show the result without running
<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
21 3
+ joins text and adds numbers. Convert first.
Music Put a number inside text
Show the result without running
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
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
Football
homeandawayhold scores as text. Store their total as a number inanswer.Hint
int(home) + int(away)
Show the answer
Music Make
answerthe text215 seconds, built from the number inlength.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
Slower version: Python from zero, 2.2 Numbers and maths
Examples
Shop Add VAT and round
Show the result without running
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
3.5833333333333335 3 35
215 seconds is 3 minutes and 35 seconds.
Jobs A percentage rise
Show the result without running
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
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
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
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
Slower version: Python from zero, 2.5 Lists
Examples
Shop How many, and the total
Show the result without running
5 307.49
One name, five values.
Music First and last
Predict first: Which song is queue[1]?
Show the result without running
Salt Road Ferry Home
Counting starts at 0. -1 counts from the end.
Football Biggest and smallest
Show the result without running
3 0
max and min read the whole list.
Jobs An average from a list
Show the result without running
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
Football Store the total number of goals in the list in
answer.Hint
One word does it.
Show the answer
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, afterSlower version: Python from zero, 2.8 Repeating things: for loops
Examples
Music Print every song
Show the result without running
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
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
so far: 0 so far: 2 so far: 5 so far: 6 so far: 8
8
Start at 0 before the loop. Add each item inside the loop.
Jobs Monthly pay for each salary
Show the result without running
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
Music Finish the loop so that
totalends up as the sum of all the seconds. Then setanswer = total.Hint
Inside the loop: total = total + s
Show the answer
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"Slower version: Python from zero, 2.7 Making decisions
Examples
Shop Label a price
Show the result without running
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
'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
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
True True
and needs both. or needs one.
App Stop at the first match
Show the result without running
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
Jobs Make
answerthe texthighif salary is 50,000 or more, andstandardif not.Hint
"Or more" means
>=.Show the answer
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, sortedSlower version: Python from zero, 2.5 Lists
Examples
Shop Build a list in a loop
Show the result without running
[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
['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
True False
in gives True or False. It checks exact text.
App Unique values
Show the result without running
{'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
[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
Music Store the last three songs of the queue, in order, in
answer.Hint
A slice with a negative start.
Show the answer
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}"Slower version: Python from zero, 2.3 Text (strings)
Examples
Shop Tidy messy names
Show the result without running
['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
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
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
['Half Light', 'Harbour Lights']
Lower-case both sides so the search ignores capitals.
Shop Part of an email address
Show the result without running
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
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
Jobs Build the text
Data offer: €52,000with an f-string, fromfamilyandsalary. Store it inanswer.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)Slower version: Python from zero, 2.6 Dictionaries
Examples
Shop Look up a price
Show the result without running
59.0
Faster and clearer than searching a list.
Jobs A default for a missing key
Show the result without running
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
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
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
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
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) # 6Slower version: Python from zero, 2.9 Functions
Examples
Shop Price with VAT
Show the result without running
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
[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
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
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
Football Write
result(home, away)that returnsH,DorA. Then store[result(2, 1), result(0, 0), result(1, 3)]inanswer.Hint
if, elif, else, each with a return.
Show the answer
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)]inanswer.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 dictionaryExamples
Shop The loop and the one-liner
Show the result without running
[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
[172, 305, 203, 175]
The if at the end filters.
Jobs A dictionary comprehension
Show the result without running
{'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
['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
Music Store a list of the titles that start with S, in capitals, in
answer.Hint
t.upper()for each t, withif t.startswith("S").Show the answer
Jobs Build a dictionary from family to salary, leaving out any salary that is
None. Store it inanswer.Hint
if s is not Noneat 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 textSame idea in SQL: GROUP BY
Examples
Football Count by hand
Show the result without running
{'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
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
70 rows
{'order_id': '1', 'customer_id': '15', 'product_id': '1', 'quantity': '1', 'order_date': '2025-01-03', 'status': 'delivered', 'discount': ''}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
[('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
{'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
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}inanswer. Matches not played yet have empty goals.Hint
Skip rows where
home_goals == "". Convert goals with int before comparing.Show the answer
App From
events.csv, store the three most common event names with their counts, most common first, as Counter'smost_commongives 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
Same idea in SQL: ORDER BY and LIMIT: top N
Examples
Shop Sort records by one field
Show the result without running
['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
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
[('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
[('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
App Store the
user_idwith the most sessions inanswer.Hint
max with key=sessions.get
Show the answer
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 columnsSlower version: Python from zero, 3.1 A DataFrame, and reading a CSV. Same idea in SQL: SELECT, aliases and maths
Examples
Shop The first five rows
Show the result without running
| order_id | customer_id | product_id | quantity | order_date | status | discount |
|---|---|---|---|---|---|---|
| 1 | 15 | 1 | 1 | 2025-01-03 | delivered | NaN |
| 2 | 15 | 2 | 2 | 2025-01-09 | delivered | NaN |
| 3 | 3 | 5 | 1 | 2025-01-13 | delivered | NaN |
| 4 | 3 | 11 | 1 | 2025-01-14 | delivered | NaN |
| 5 | 10 | 12 | 1 | 2025-01-18 | delivered | NaN |
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
(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
| match_id | int64 |
| match_date | object |
| home_team_id | int64 |
| away_team_id | int64 |
| home_goals | float64 |
| away_goals | float64 |
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
<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
| base_salary | |
|---|---|
| count | 44.0 |
| mean | 53159.0909 |
| std | 15659.8185 |
| min | 29500.0 |
| 25% | 41375.0 |
| 50% | 48500.0 |
| 75% | 64125.0 |
| max | 92000.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
Jobs How many rows does
companies.csvhave? Store the number inanswer.Hint
len(companies) or companies.shape[0].
Show the answer
Music Store the longest single play, the biggest
seconds_playedinstreams.csv, inanswer.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"])Slower version: Python from zero, 3.3 Picking columns. Same idea in SQL: SELECT, aliases and maths
Examples
Shop Prices with VAT added
Show the result without running
| name | price | price_with_vat |
|---|---|---|
| Trail Runner Shoes | 89.0 | 109.47 |
| Camping Stove | 45.5 | 55.96 |
| Rain Jacket | 120.0 | 147.6 |
| Board Game: Harbour | 34.99 | 43.04 |
| Puzzle 1000 | 18.0 | 22.14 |
| Card Game: Gulls | 12.5 | 15.38 |
| Chef Knife | 59.0 | 72.57 |
| Cast Iron Pan | 42.0 | 51.66 |
| Coffee Grinder | 75.0 | 92.25 |
| Novel: Low Tide | 14.99 | 18.44 |
| Cookbook: Brown Bread | 24.0 | 29.52 |
| Atlas of Islands | 38.0 | 46.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
| match_id | home_goals | away_goals | total_goals | |
|---|---|---|---|---|
| 24 | 25 | 0.0 | 3.0 | 3.0 |
| 25 | 26 | 2.0 | 1.0 | 3.0 |
| 26 | 27 | NaN | NaN | NaN |
| 27 | 28 | NaN | NaN | NaN |
| 28 | 29 | NaN | NaN | NaN |
| 29 | 30 | NaN | NaN | NaN |
Maths with a blank gives a blank (NaN). The postponed matches have no total.
Music Song length in minutes
Show the result without running
| title | length_sec | minutes |
|---|---|---|
| Salt Road | 265 | 4.4 |
| Kite Weather | 201 | 3.4 |
| Half Light | 203 | 3.4 |
| Ferry Home | 192 | 3.2 |
| Glass Tide | 249 | 4.2 |
In Python, / always keeps the decimals. SQLite would drop them.
App Glue text columns together
Show the result without running
| user_id | segment |
|---|---|
| 1 | web / DE |
| 2 | android / IE |
| 3 | web / IE |
| 4 | web / DE |
| 5 | web / UK |
+ joins text columns, row by row.
Jobs Rename, then work out a new column
Show the result without running
| offer_id | salary | monthly |
|---|---|---|
| 1 | 33000.0 | 2750.0 |
| 2 | 37000.0 | 3083.0 |
| 3 | 61000.0 | 5083.0 |
| 4 | 53500.0 | 4458.0 |
| 5 | 74000.0 | 6167.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
Music Return a table of each listener's
nameandplan, withplanrenamedsubscription. This one checks the column names too.Hint
Pick two columns, then .rename(columns={...}).
Show the answer
Shop Return a table of each product's
nameand 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")]Slower version: Python from zero, 3.4 Filtering rows. Same idea in SQL: WHERE with AND, OR, IN, BETWEEN, LIKE
Examples
Shop Delivered orders of two or more items
Show the result without running
| order_id | customer_id | product_id | quantity | order_date | status | discount | |
|---|---|---|---|---|---|---|---|
| 1 | 2 | 15 | 2 | 2 | 2025-01-09 | delivered | NaN |
| 6 | 7 | 17 | 11 | 2 | 2025-01-21 | delivered | NaN |
| 11 | 12 | 13 | 2 | 2 | 2025-01-28 | delivered | NaN |
| 27 | 28 | 3 | 12 | 2 | 2025-03-01 | delivered | NaN |
| 29 | 30 | 18 | 4 | 2 | 2025-03-03 | delivered | NaN |
| 30 | 31 | 5 | 10 | 3 | 2025-03-07 | delivered | NaN |
| 31 | 32 | 11 | 11 | 2 | 2025-03-09 | delivered | NaN |
| 32 | 33 | 13 | 8 | 2 | 2025-03-20 | delivered | 10.0 |
| 39 | 40 | 12 | 8 | 2 | 2025-04-06 | delivered | 5.0 |
| 40 | 41 | 5 | 5 | 2 | 2025-04-08 | delivered | NaN |
| 43 | 44 | 9 | 3 | 3 | 2025-04-16 | delivered | 5.0 |
| 46 | 47 | 10 | 6 | 2 | 2025-04-21 | delivered | NaN |
| 47 | 48 | 16 | 1 | 2 | 2025-04-22 | delivered | 5.0 |
| 48 | 49 | 3 | 11 | 2 | 2025-04-25 | delivered | NaN |
| 51 | 52 | 5 | 12 | 2 | 2025-05-08 | delivered | NaN |
| 52 | 53 | 12 | 7 | 2 | 2025-05-10 | delivered | NaN |
| 53 | 54 | 13 | 2 | 3 | 2025-05-10 | delivered | NaN |
| 54 | 55 | 10 | 8 | 3 | 2025-05-13 | delivered | 5.0 |
| 55 | 56 | 3 | 3 | 3 | 2025-05-14 | delivered | 5.0 |
| 57 | 58 | 6 | 8 | 3 | 2025-06-01 | delivered | NaN |
| 60 | 61 | 1 | 10 | 2 | 2025-06-04 | delivered | NaN |
| 69 | 70 | 5 | 5 | 2 | 2025-04-08 | delivered | NaN |
& means both tests must pass. Each test goes in its own brackets.
Music Look at the mask itself
Show the result without running
[True, False, False, False, False, False, False, False]
| song_id | title | artist_id | length_sec | |
|---|---|---|---|---|
| 0 | 1 | Salt Road | 1 | 265 |
| 9 | 10 | Slow Rain | 4 | 152 |
| 15 | 16 | Static Bloom | 6 | 218 |
| 19 | 20 | Soft Focus | 8 | 215 |
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
| offer_id | company_id | job_family | level | base_salary | offered_at | accepted_at | status | |
|---|---|---|---|---|---|---|---|---|
| 4 | 5 | 2 | Data | Senior | 74000.0 | 2023-02-06 | 2023-02-10 | accepted |
| 24 | 25 | 5 | Data | Senior | 64500.0 | 2023-09-22 | 2023-10-02 | accepted |
| 25 | 26 | 2 | Data | Senior | 83000.0 | 2023-12-05 | 2023-12-17 | accepted |
| 27 | 28 | 7 | Data | Mid | 54500.0 | 2024-01-31 | 2024-02-01 | accepted |
| 28 | 29 | 8 | Design | Senior | 64000.0 | 2024-01-31 | 2024-02-03 | accepted |
| 35 | 36 | 3 | Data | Mid | 57000.0 | 2024-05-12 | 2024-05-13 | accepted |
| 36 | 37 | 10 | Design | Senior | 68000.0 | 2024-05-26 | 2024-06-05 | accepted |
| 40 | 41 | 1 | Design | Senior | 68500.0 | 2024-09-22 | 2024-10-02 | accepted |
| 42 | 43 | 10 | Design | Senior | 74000.0 | 2024-12-08 | 2024-12-11 | accepted |
| 43 | 44 | 8 | Data | Senior | 75000.0 | 2024-12-21 | 2024-12-27 | accepted |
isin is a short way to write several ORs on one column.
Football Matches in September 2024
Show the result without running
| match_id | match_date | home_team_id | away_team_id | home_goals | away_goals | |
|---|---|---|---|---|---|---|
| 15 | 16 | 2024-09-07 | 3 | 4 | 2.0 | 5.0 |
| 16 | 17 | 2024-09-07 | 2 | 4 | 3.0 | 0.0 |
| 17 | 18 | 2024-09-07 | 1 | 2 | 1.0 | 1.0 |
| 18 | 19 | 2024-09-14 | 4 | 2 | 3.0 | 2.0 |
| 19 | 20 | 2024-09-14 | 2 | 6 | 3.0 | 1.0 |
| 20 | 21 | 2024-09-14 | 1 | 5 | 2.0 | 1.0 |
| 21 | 22 | 2024-09-21 | 5 | 4 | 0.0 | 1.0 |
| 22 | 23 | 2024-09-21 | 4 | 3 | 2.0 | 1.0 |
| 23 | 24 | 2024-09-21 | 5 | 2 | 1.0 | 1.0 |
| 24 | 25 | 2024-09-28 | 3 | 1 | 0.0 | 3.0 |
| 25 | 26 | 2024-09-28 | 5 | 1 | 2.0 | 1.0 |
| 26 | 27 | 2024-09-28 | 6 | 3 | NaN | NaN |
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
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
Jobs Return
offer_idandbase_salaryfor Junior offers paying from 35,000 to 40,000, both ends included.Hint
level == "Junior" and .between(35000, 40000).
Show the answer
Shop Find customers in Cork or Galway who signed up before 1 November 2024. Return
nameandcity.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")Slower version: Python from zero, 3.5 Sorting. Same idea in SQL: ORDER BY and LIMIT: top N
Examples
Shop The three dearest products
Show the result without running
| product_id | name | category | price | |
|---|---|---|---|---|
| 2 | 3 | Rain Jacket | Outdoor | 120.0 |
| 0 | 1 | Trail Runner Shoes | Outdoor | 89.0 |
| 8 | 9 | Coffee Grinder | Kitchen | 75.0 |
Biggest first needs ascending=False.
Music nlargest does both steps
Show the result without running
| song_id | title | artist_id | length_sec | |
|---|---|---|---|---|
| 17 | 18 | Last Tram | 7 | 310 |
| 5 | 6 | Paper Moon | 2 | 305 |
| 18 | 19 | Iron Bridge | 7 | 300 |
Same as sort then head, in one call.
Jobs Sort by two columns
Show the result without running
| offer_id | level | base_salary | |
|---|---|---|---|
| 39 | 40 | Junior | 52000.0 |
| 17 | 18 | Junior | 48000.0 |
| 18 | 19 | Junior | 48000.0 |
| 38 | 39 | Junior | 45000.0 |
| 23 | 24 | Junior | 44500.0 |
| 41 | 42 | Junior | 44000.0 |
| 34 | 35 | Junior | 43000.0 |
| 5 | 6 | Junior | 41500.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
| match_id | match_date | home_team_id | away_team_id | home_goals | away_goals | |
|---|---|---|---|---|---|---|
| 19 | 20 | 2024-09-14 | 2 | 6 | 3.0 | 1.0 |
| 2 | 3 | 2024-08-03 | 2 | 3 | 3.0 | 0.0 |
| 26 | 27 | 2024-09-28 | 6 | 3 | NaN | NaN |
| 27 | 28 | 2024-10-05 | 3 | 6 | NaN | NaN |
| 28 | 29 | 2024-10-05 | 1 | 3 | NaN | NaN |
| 29 | 30 | 2024-10-05 | 6 | 4 | NaN | NaN |
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
App The 5 earliest sign-ups: return
user_idandsignup_date, earliest first. Break ties by loweruser_id.Hint
Sort by ["signup_date", "user_id"], then head(5).
Show the answer
Shop The top 3 orders by quantity, biggest first. Break ties by lower
order_id. Returnorder_idandquantity.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
Same idea in SQL: COUNT(DISTINCT)
Examples
Shop Orders by status
Show the result without running
| status | count |
|---|---|
| delivered | 57 |
| returned | 8 |
| cancelled | 5 |
The same as Counter, as a Series.
Music Shares, not counts
Show the result without running
| plan | proportion |
|---|---|
| free | 0.6 |
| premium | 0.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
29 users counted, out of 36
| referrer | count |
|---|---|
| ad | 13 |
| search | 9 |
| NaN | 7 |
| friend | 7 |
Seven users have no referrer. Without dropna=False they vanish from the count.
Jobs Rows against different values
Show the result without running
45 offers 11 companies made them
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
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
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
Slower version: Python from zero, 3.7 Cleaning: missing values and duplicates. Same idea in SQL: Finding NULLs
Examples
Shop Blanks in every column
Show the result without running
| customer_id | 0 |
| name | 0 |
| city | 1 |
| 2 | |
| signup_date | 0 |
The first thing to run on any new file.
Football Matches not played yet
Show the result without running
| match_id | match_date | home_team_id | away_team_id | home_goals | away_goals | |
|---|---|---|---|---|---|---|
| 26 | 27 | 2024-09-28 | 6 | 3 | NaN | NaN |
| 27 | 28 | 2024-10-05 | 3 | 6 | NaN | NaN |
| 28 | 29 | 2024-10-05 | 1 | 3 | NaN | NaN |
| 29 | 30 | 2024-10-05 | 6 | 4 | NaN | NaN |
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
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
23
| referrer | count |
|---|---|
| search | 9 |
| NaN | 7 |
| friend | 7 |
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
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
Jobs Store a list of the
offer_idvalues for offers never accepted (blankaccepted_at).Hint
Filter with .isna(), pick offer_id, then .tolist().
Show the answer
Music Return each listener's
nameandcountry, with a blank country shown asUnknown. 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 pairSlower version: Python from zero, 3.9 Group and summarise: groupby. Same idea in SQL: GROUP BY
Examples
Shop Items bought by each customer
Show the result without running
| customer_id | quantity |
|---|---|
| 5 | 11 |
| 3 | 11 |
| 1 | 9 |
| 10 | 8 |
| 2 | 7 |
The group key becomes the index of the result.
Jobs Average salary by family
Show the result without running
| job_family | base_salary |
|---|---|
| Data | 55727.0 |
| Design | 54389.0 |
| Engineering | 57125.0 |
| Product | 56821.0 |
| Sales | 35417.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
| song_id | |
|---|---|
| 5 | 29 |
| 4 | 18 |
| 1 | 14 |
size counts rows in each group.
App Group by two columns
Show the result without running
| platform | country | users |
|---|---|---|
| android | DE | 1 |
| android | IE | 10 |
| android | UK | 2 |
| android | US | 3 |
| ios | IE | 5 |
| ios | UK | 3 |
| ios | US | 1 |
| web | DE | 6 |
| web | IE | 3 |
| web | UK | 1 |
| web | US | 1 |
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
| home_team_id | home_goals |
|---|---|
| 1 | 7.0 |
| 2 | 12.0 |
| 3 | 6.0 |
| 4 | 7.0 |
| 5 | 4.0 |
| 6 | 2.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
Jobs Average
base_salaryfor eachlevel, rounded to 0 decimals. Return level and the average.Hint
groupby level, pick base_salary, .mean().round(0).
Show the answer
Music Total
seconds_playedfor eachlistener_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 SQLSlower version: Python from zero, 3.9 Group and summarise: groupby. Same idea in SQL: HAVING against WHERE
Examples
Shop A summary per customer
Show the result without running
| customer_id | orders | units | last_order |
|---|---|---|---|
| 1 | 8 | 9 | 2025-06-04 |
| 2 | 6 | 7 | 2025-04-28 |
| 3 | 7 | 11 | 2025-05-14 |
| 4 | 3 | 3 | 2025-06-14 |
| 5 | 6 | 11 | 2025-06-24 |
max on YYYY-MM-DD text gives the latest date.
Music Count a condition per group
Show the result without running
| listener_id | plays | skips |
|---|---|---|
| 1 | 17 | 0 |
| 2 | 8 | 1 |
| 3 | 17 | 1 |
| 4 | 6 | 0 |
| 5 | 12 | 0 |
Summing True and False counts the Trues.
Jobs Filter the groups afterwards
Show the result without running
| job_family | n | avg_salary |
|---|---|---|
| Data | 11 | 55727.0 |
| Design | 10 | 54389.0 |
| Product | 14 | 56821.0 |
Filter rows before grouping (like WHERE), or groups after (like HAVING).
Football Several stats on a whole table
Show the result without running
| home_goals | away_goals | |
|---|---|---|
| sum | 38.0 | 34.0 |
| mean | 1.4615 | 1.3077 |
| max | 3.0 | 5.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
Jobs For each
job_familywith 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
Shop For each
customer_id: the number of orders and the first order date. Name the columnscustomer_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
Slower version: Python from zero, 3.10 Joining tables: merge. Same idea in SQL: LEFT JOIN and finding what is missing
Examples
Shop Orders with product details
Show the result without running
| order_id | name | quantity | price | line_total |
|---|---|---|---|---|
| 1 | Trail Runner Shoes | 1 | 89.0 | 89.0 |
| 2 | Camping Stove | 2 | 45.5 | 91.0 |
| 3 | Puzzle 1000 | 1 | 18.0 | 18.0 |
| 4 | Cookbook: Brown Bread | 1 | 24.0 | 24.0 |
| 5 | Atlas of Islands | 1 | 38.0 | 38.0 |
Each order picks up its product's name and price.
Music Three tables: plays per artist
Show the result without running
| name | |
|---|---|
| Mara Vale | 67 |
| The Gannets | 28 |
| Neon Curlew | 24 |
| Low Kettle | 22 |
| Driftwood Kids | 21 |
| Brass Harbour | 4 |
| Sally Gap | 4 |
Chain merges one after another, like JOIN after JOIN.
Football Keys with different names
Show the result without running
| match_id | name | home_goals |
|---|---|---|
| 1 | Shannon Celtic | 0.0 |
| 2 | Riverside Rovers | 2.0 |
| 3 | Harbour United | 3.0 |
| 4 | Shannon Celtic | 1.0 |
| 5 | Harbour United | 2.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
| customer_id | name | |
|---|---|---|
| 70 | 19 | Meabh Carroll |
| 71 | 20 | Lorcan Hayes |
A left merge keeps everyone. left_only marks the rows with no order.
Jobs Check the row count
Show the result without running
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
Shop Return the
nameof every customer who has never placed an order.Hint
Left merge with indicator=True, keep left_only.
Show the answer
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 totalsSame idea in SQL: CASE inside SUM: conditional counts and pivots
Examples
Shop Orders by month and status
Show the result without running
| month | cancelled | delivered | returned |
|---|---|---|---|
| 2025-01 | 1 | 13 | 1 |
| 2025-02 | 2 | 8 | 2 |
| 2025-03 | 1 | 8 | 0 |
| 2025-04 | 1 | 11 | 3 |
| 2025-05 | 0 | 7 | 0 |
| 2025-06 | 0 | 10 | 2 |
.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
| level | Data | Design | Engineering | Product | Sales |
|---|---|---|---|---|---|
| Junior | 41000.0 | 37250.0 | 48000.0 | 43500.0 | 32000.0 |
| Mid | 55750.0 | 46833.0 | 66250.0 | 56800.0 | 42250.0 |
| Senior | 74125.0 | 68625.0 | NaN | 83500.0 | NaN |
A blank cell means no offers for that pair.
Music Plays by country and plan
Show the result without running
| country | free | premium |
|---|---|---|
| DE | 26 | 0 |
| FR | 6 | 29 |
| IE | 27 | 17 |
| UK | 4 | 61 |
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
| platform | ad | friend | search | All |
|---|---|---|---|---|
| android | 5 | 5 | 3 | 13 |
| ios | 5 | 1 | 3 | 9 |
| web | 3 | 1 | 3 | 7 |
| All | 13 | 7 | 9 | 29 |
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
App Count users by
platform(rows) andcountry(columns), with 0 where there are none.Hint
pd.crosstab with platform first.
Show the answer
Jobs Count offers by
level(rows) andstatus(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)Slower version: Python from zero, 3.6 Making new columns. Same idea in SQL: CASE WHEN: buckets and labels
Examples
Music if/else on a column
Show the result without running
| kind | count |
|---|---|
| play | 165 |
| skip | 5 |
One line instead of a loop over 170 rows.
Shop Price bands with pd.cut
Show the result without running
| name | price | band |
|---|---|---|
| Trail Runner Shoes | 89.0 | over 50 |
| Camping Stove | 45.5 | 20 to 50 |
| Rain Jacket | 120.0 | over 50 |
| Board Game: Harbour | 34.99 | 20 to 50 |
| Puzzle 1000 | 18.0 | under 20 |
| Card Game: Gulls | 12.5 | under 20 |
| Chef Knife | 59.0 | over 50 |
| Cast Iron Pan | 42.0 | 20 to 50 |
| Coffee Grinder | 75.0 | over 50 |
| Novel: Low Tide | 14.99 | under 20 |
| Cookbook: Brown Bread | 24.0 | 20 to 50 |
| Atlas of Islands | 38.0 | 20 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 | count |
|---|---|
| H | 13 |
| A | 8 |
| D | 5 |
| not played | 4 |
A blank fails every test, so postponed matches fall to the default.
App Map codes to names
Show the result without running
| user_id | country | country_name | |
|---|---|---|---|
| 31 | 32 | UK | United Kingdom |
| 32 | 33 | IE | Ireland |
| 33 | 34 | IE | Ireland |
| 34 | 35 | IE | Ireland |
| 35 | 36 | IE | Ireland |
A code missing from the dictionary becomes NaN. US is not in it.
Jobs Your own function with apply
Show the result without running
| band | count |
|---|---|
| under 60k | 30 |
| 60k plus | 14 |
| unknown | 1 |
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
Football Add a
resultcolumn:H,A,D, orPfor a postponed match. Returnmatch_idandresult.Hint
np.select with three tests and default="P".
Show the answer
Jobs Band salaries: under 40,000 is
low, 40,000 up to under 60,000 ismid, 60,000 and over ishigh. 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 resampleSlower version: Python from zero, 3.11 Working with dates. Same idea in SQL: Dates: by month, by weekday, days between
Examples
Music Plays by weekday
Show the result without running
| weekday | count |
|---|---|
| Thursday | 28 |
| Friday | 26 |
| Tuesday | 24 |
| Wednesday | 24 |
| Saturday | 23 |
| Sunday | 23 |
| Monday | 22 |
.dt only works once the column is a real date.
Shop Orders per month
Show the result without running
| order_date | |
|---|---|
| 2025-01 | 15 |
| 2025-02 | 12 |
| 2025-03 | 9 |
| 2025-04 | 15 |
| 2025-05 | 7 |
| 2025-06 | 12 |
parse_dates converts while reading. A Period like 2025-03 is a whole month.
Jobs Days between two dates
Show the result without running
| offer_id | offered_at | accepted_at | days_to_accept |
|---|---|---|---|
| 1 | 2023-01-05 | 2023-01-13 | 8.0 |
| 2 | 2023-01-12 | 2023-01-25 | 13.0 |
| 3 | 2023-01-16 | NaT | NaN |
| 4 | 2023-01-31 | 2023-02-13 | 13.0 |
| 5 | 2023-02-06 | 2023-02-10 | 4.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
| signup_date | user_id |
|---|---|
| 2025-01-01 | 12 |
| 2025-02-01 | 12 |
| 2025-03-01 | 12 |
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
12 matches in September
| match_id | match_date | |
|---|---|---|
| 15 | 16 | 2024-09-07 |
| 16 | 17 | 2024-09-07 |
| 17 | 18 | 2024-09-07 |
| 18 | 19 | 2024-09-14 |
| 19 | 20 | 2024-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
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
Jobs Average number of days from
offered_attoaccepted_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)Slower version: Python from zero, 3.12 Change over time: pct_change. Same idea in SQL: LAG: change against the previous period
Examples
Shop Orders per month, against the month before
Show the result without running
| month | orders | prev | change | pct |
|---|---|---|---|---|
| 2025-01 | 15 | NaN | NaN | NaN |
| 2025-02 | 12 | 15.0 | -3.0 | -20.0 |
| 2025-03 | 9 | 12.0 | -3.0 | -25.0 |
| 2025-04 | 15 | 9.0 | 6.0 | 66.7 |
| 2025-05 | 7 | 15.0 | -8.0 | -53.3 |
| 2025-06 | 12 | 7.0 | 5.0 | 71.4 |
The first month has no month before it, so it gets NaN.
Music Day-on-day change
Show the result without running
| streamed_on | |
|---|---|
| 2025-03-01 | NaN |
| 2025-03-02 | -2.0 |
| 2025-03-03 | 1.0 |
| 2025-03-04 | 2.0 |
| 2025-03-05 | -4.0 |
| 2025-03-06 | 3.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
offered_at 2023 52960.0 2024 53421.0 Name: base_salary, dtype: float64
| offered_at | base_salary |
|---|---|
| 2023 | NaN |
| 2024 | 0.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
| user_id | event_name | event_time | hours_since | |
|---|---|---|---|---|
| 19 | 1 | signup | 2025-01-16 09:11:00 | NaN |
| 20 | 1 | onboarding_done | 2025-01-16 11:54:00 | 2.7 |
| 21 | 1 | first_post | 2025-01-17 15:55:00 | 28.0 |
| 30 | 1 | session_start | 2025-01-21 20:18:00 | 100.4 |
| 53 | 1 | session_start | 2025-02-06 20:14:00 | 383.9 |
| 128 | 1 | session_start | 2025-03-20 08:38:00 | 996.4 |
| 6 | 2 | signup | 2025-01-07 09:52:00 | NaN |
| 7 | 2 | onboarding_done | 2025-01-07 11:19:00 | 1.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
Shop Which month had the biggest drop in order count against the month before? Return one row with
month(YYYY-MM) andchange(a negative number).Hint
Monthly counts, .diff(), then nsmallest(1, "change").
Show the answer
Music Daily plays and the change from the day before. Return
streamed_on,playsandchange, 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()Same idea in SQL: Running totals with SUM OVER
Examples
Shop Orders so far, month by month
Show the result without running
| order_date | orders | so_far |
|---|---|---|
| 2025-01 | 15 | 15 |
| 2025-02 | 12 | 27 |
| 2025-03 | 9 | 36 |
| 2025-04 | 15 | 51 |
| 2025-05 | 7 | 58 |
| 2025-06 | 12 | 70 |
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
| streamed_on | plays | avg_7 |
|---|---|---|
| 2025-03-01 | 7 | NaN |
| 2025-03-02 | 5 | NaN |
| 2025-03-03 | 6 | NaN |
| 2025-03-04 | 8 | NaN |
| 2025-03-05 | 4 | NaN |
| 2025-03-06 | 7 | NaN |
| 2025-03-07 | 5 | 6.0 |
| 2025-03-08 | 6 | 5.9 |
| 2025-03-09 | 5 | 5.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
| offer_id | job_family | offered_at | nth_in_family | |
|---|---|---|---|---|
| 0 | 1 | Sales | 2023-01-05 | 1 |
| 1 | 2 | Data | 2023-01-12 | 1 |
| 2 | 3 | Product | 2023-01-16 | 1 |
| 3 | 4 | Product | 2023-01-31 | 2 |
| 4 | 5 | Data | 2023-02-06 | 2 |
| 5 | 6 | Data | 2023-02-23 | 3 |
| 6 | 7 | Design | 2023-03-12 | 1 |
| 7 | 8 | Design | 2023-03-15 | 2 |
cumcount starts at 0, so add 1.
Football Goals so far, round by round
Show the result without running
| match_date | goals | so_far |
|---|---|---|
| 2024-08-03 | 9.0 | 9.0 |
| 2024-08-10 | 8.0 | 17.0 |
| 2024-08-17 | 7.0 | 24.0 |
| 2024-08-24 | 6.0 | 30.0 |
| 2024-08-31 | 6.0 | 36.0 |
| 2024-09-07 | 12.0 | 48.0 |
| 2024-09-14 | 12.0 | 60.0 |
| 2024-09-21 | 6.0 | 66.0 |
| 2024-09-28 | 6.0 | 72.0 |
| 2024-10-05 | 0.0 | 72.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
App Sign-ups per
signup_dateand a running total. Returnsignup_date,signupsandrunning, earliest date first.Hint
groupby("signup_date").size().reset_index(name="signups"), then cumsum.
Show the answer
Music Daily plays and a 3-day rolling average, rounded to 1 decimal. Return
streamed_on,playsandavg_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)Same idea in SQL: Top N per group
Examples
Shop How ties are ranked
Predict first: With dense, what rank does 59.0 get?
Show the result without running
| price | min | dense | first |
|---|---|---|---|
| 120.0 | 1.0 | 1.0 | 1.0 |
| 89.0 | 2.0 | 2.0 | 2.0 |
| 89.0 | 2.0 | 2.0 | 3.0 |
| 59.0 | 4.0 | 3.0 | 4.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
| job_family | offer_id | base_salary | |
|---|---|---|---|
| 25 | Data | 26 | 83000.0 |
| 43 | Data | 44 | 75000.0 |
| 42 | Design | 43 | 74000.0 |
| 40 | Design | 41 | 68500.0 |
| 14 | Engineering | 15 | 69000.0 |
| 29 | Engineering | 30 | 63500.0 |
| 44 | Product | 45 | 92000.0 |
| 22 | Product | 23 | 85000.0 |
| 8 | Sales | 9 | 42500.0 |
| 37 | Sales | 38 | 42000.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
| artist_id | title | plays | rank_in_artist | |
|---|---|---|---|---|
| 0 | 1 | Salt Road | 14 | 1.0 |
| 1 | 1 | Kite Weather | 8 | 2.0 |
| 2 | 1 | Half Light | 6 | 3.0 |
| 4 | 2 | Glass Tide | 29 | 1.0 |
| 3 | 2 | Ferry Home | 18 | 2.0 |
| 5 | 2 | Paper Moon | 12 | 3.0 |
| 6 | 2 | Long Grass | 8 | 4.0 |
| 7 | 3 | Copper Sky | 14 | 1.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
| home_team_id | match_date | home_goals | |
|---|---|---|---|
| 1 | 1 | 2024-08-03 | 2.0 |
| 2 | 2 | 2024-08-03 | 3.0 |
| 9 | 3 | 2024-08-24 | 2.0 |
| 18 | 4 | 2024-09-14 | 3.0 |
| 25 | 5 | 2024-09-28 | 2.0 |
| 6 | 6 | 2024-08-17 | 1.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
Jobs The highest-paid offer in each industry, with the company name. Ties: lower
offer_id. Returnindustry,name,base_salary.Hint
Merge offers with companies, sort by salary down and offer_id up, groupby("industry").head(1).
Show the answer
Music Each listener's most-streamed song. Ties: lower
song_id. Returnlistener_idandsong_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 ideaSlower version: Python from zero, 3.7 Cleaning: missing values and duplicates. Same idea in SQL: Finding and removing duplicates
Examples
Shop Find a double-submitted order
Show the result without running
| order_id | customer_id | product_id | quantity | order_date | status | discount | |
|---|---|---|---|---|---|---|---|
| 40 | 41 | 5 | 5 | 2 | 2025-04-08 | delivered | NaN |
| 69 | 70 | 5 | 5 | 2 | 2025-04-08 | delivered | NaN |
keep=False flags every copy, so you see both rows.
App Rows before and after
Show the result without running
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
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
| stream_id | listener_id | song_id | streamed_on | seconds_played | |
|---|---|---|---|---|---|
| 140 | 141 | 1 | 5 | 2025-03-24 | 186 |
| 162 | 163 | 2 | 5 | 2025-03-28 | 80 |
| 154 | 155 | 3 | 5 | 2025-03-26 | 154 |
| 163 | 164 | 4 | 5 | 2025-03-28 | 249 |
| 159 | 160 | 5 | 19 | 2025-03-27 | 300 |
| 167 | 168 | 6 | 1 | 2025-03-28 | 160 |
| 144 | 145 | 7 | 9 | 2025-03-24 | 153 |
| 161 | 162 | 8 | 12 | 2025-03-27 | 14 |
| 134 | 135 | 9 | 12 | 2025-03-22 | 101 |
| 156 | 157 | 11 | 14 | 2025-03-26 | 207 |
| 169 | 170 | 12 | 2 | 2025-03-28 | 201 |
| 146 | 147 | 13 | 4 | 2025-03-24 | 192 |
| 157 | 158 | 14 | 10 | 2025-03-26 | 95 |
| 131 | 132 | 15 | 1 | 2025-03-21 | 265 |
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
| home_team_id | match_id | match_date | |
|---|---|---|---|
| 28 | 1 | 29 | 2024-10-05 |
| 19 | 2 | 20 | 2024-09-14 |
| 27 | 3 | 28 | 2024-10-05 |
| 22 | 4 | 23 | 2024-09-21 |
| 25 | 5 | 26 | 2024-09-28 |
| 29 | 6 | 30 | 2024-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
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
Shop Each customer's most recent order. Ties on date: higher
order_id. Returncustomer_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"))Slower version: Python from zero, 3.8 Reading JSON
Examples
Jobs Look at the top, then go down
Show the result without running
dict_keys(['page', 'count', 'results']) 8 results
{'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
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
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
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
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
Jobs From
offers_api.json, store a list of the company names for offers whose perks includeremote, 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 itemExamples
Jobs Nested keys become columns
Show the result without running
| offer_id | perks | company.name | company.city | role.family | role.level | salary.base | salary.currency |
|---|---|---|---|---|---|---|---|
| 2 | ['pension', 'remote'] | Willowby Insurance | Galway | Data | Junior | 37000 | EUR |
| 3 | ['pension', 'bonus'] | Umberfield Software | London | Product | Mid | 61000 | EUR |
| 4 | [] | Quillstone Media | London | Product | Mid | 53500 | EUR |
| 7 | ['remote', 'bonus', 'pension'] | Brightwell Analytics | Dublin | Data | Senior | 78000 | EUR |
| 9 | ['car'] | Larkspur Freight | None | Sales | Junior | 34000 | EUR |
| 12 | ['remote'] | Pixelmoor Games | Dublin | Design | Mid | 52000 | EUR |
| 15 | ['pension', 'bonus'] | Kettlebrook Bank | Dublin | Engineering | Senior | 82000 | EUR |
| 20 | ['remote', 'pension'] | Brightwell Analytics | Dublin | Design | Junior | 38000 | EUR |
Nested names are joined with dots: company.name, salary.base.
Shop One row per item
Show the result without running
| sku | name | qty | price | order_id | customer.name |
|---|---|---|---|---|---|
| P05 | Puzzle 1000 | 2 | 18.0 | 101 | Aoife Byrne |
| P10 | Novel: Low Tide | 1 | 14.99 | 101 | Aoife Byrne |
| P03 | Rain Jacket | 1 | 120.0 | 102 | Ciara Brennan |
| P07 | Chef Knife | 1 | 59.0 | 103 | Cian Walsh |
| P08 | Cast Iron Pan | 1 | 42.0 | 103 | Cian Walsh |
| P09 | Coffee Grinder | 1 | 75.0 | 103 | Cian Walsh |
| P06 | Card Game: Gulls | 3 | 12.5 | 104 | Tadhg Burke |
| P01 | Trail Runner Shoes | 1 | 89.0 | 105 | Niamh Kelly |
| P05 | Puzzle 1000 | 1 | 18.0 | 105 | Niamh Kelly |
| P11 | Cookbook: Brown Bread | 2 | 24.0 | 106 | Aoife 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
7 playlists
| name | songs | listener | |
|---|---|---|---|
| 0 | Morning | Salt Road | Ada |
| 0 | Morning | Half Light | Ada |
| 0 | Morning | Wren Song | Ada |
| 1 | Run | Glass Tide | Ada |
| 1 | Run | Static Bloom | Ada |
| 2 | Commute | Night Bus | Ben |
| 2 | Commute | Last Tram | Ben |
| 2 | Commute | Salt Road | Ben |
| 3 | Focus | Soft Focus | Cara |
| 3 | Focus | Blue Hour | Cara |
| 3 | Focus | Half Light | Cara |
| 4 | Sunday | Slow Rain | Cara |
| 5 | Empty | NaN | Cara |
| 6 | Mix | Glass Tide | Dev |
| 6 | Mix | Salt Road | Dev |
| 6 | Mix | Iron Bridge | Dev |
| 6 | Mix | Half Light | Dev |
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
| user_id | event | time | props.platform | props.screen | props.plan |
|---|---|---|---|---|---|
| 3 | signup | 2025-01-01T09:54:00 | web | welcome | NaN |
| 3 | session_start | 2025-01-03T11:42:00 | web | NaN | NaN |
| 4 | signup | 2025-01-03T09:18:00 | web | welcome | NaN |
| 4 | onboarding_done | 2025-01-03T11:20:00 | web | profile | NaN |
| 2 | signup | 2025-01-07T14:02:00 | NaN | NaN | NaN |
| 2 | first_post | 2025-01-08T19:30:00 | android | editor | NaN |
| 8 | signup | 2025-01-09T10:15:00 | ios | welcome | NaN |
| 8 | subscribe | 2025-01-20T08:05:00 | ios | plans | yearly |
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
Shop One row per item from
orders_api.json, withorder_id,nameandline_total(qty times price).Hint
json_normalize with record_path="items" and meta=["order_id"].
Show the answer
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)Same idea in SQL: Funnels and retention
Examples
App A four-step funnel
Show the result without running
| step | users | pct_of_start | pct_of_prev |
|---|---|---|---|
| signup | 36 | 100.0 | NaN |
| onboarding_done | 30 | 83.3 | 83.3 |
| first_post | 17 | 47.2 | 56.7 |
| subscribe | 10 | 27.8 | 58.8 |
Two percentages answer two questions. Label which one you report.
Shop Repeat customers
Show the result without running
18 customers ordered 16 ordered more than once
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
| month | sum | count | mean |
|---|---|---|---|
| 2025-01 | 2 | 12 | 0.17 |
| 2025-02 | 2 | 12 | 0.17 |
| 2025-03 | 6 | 12 | 0.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
12 listened in week 1 11 of them came back in week 4
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
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
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
| month | revenue |
|---|---|
| 2025-01 | 613.99 |
| 2025-02 | 320.99 |
| 2025-03 | 418.43 |
| 2025-04 | 991.0 |
| 2025-05 | 899.5 |
| 2025-06 | 490.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
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
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
{'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
Football Write
points_table(matches)that returns eachteam_idand itspoints(3 for a win, 1 for a draw) from played matches, counting home and away games. Storepoints_table(matches)inanswer.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
Jobs Write
offers_per_company(offers, companies)that returns every companynamewith its number of offersn, after removing duplicate offers (same in every column butoffer_id). Store the result for the two files inanswer.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()Slower version: Python from zero, 4.2 A bar chart
Examples
Shop Bar chart with a title from the data
Show the result without running
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 running
Plot the noisy line light and the smooth one dark.
Jobs Horizontal bars, sorted
Show the result without running
Sorted bars read top to bottom. Long labels fit better on a horizontal chart.
App A funnel as bars
Show the result without running
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
Jobs Before you plot, write the headline. Store the text
Product had the most offers (14), but worked out from the data, inanswer.Hint
value_counts(), then .index[0] and .iloc[0] in an f-string.
Show the answer
Music Build the table you would plot: plays per genre, highest first. Return
genreandplays.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:
| Job | Pure Python | pandas |
|---|---|---|
| Read a CSV | list(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 value | Counter(r["x"] for r in rows) | df["x"].value_counts() |
| Total per group | d[k] = d.get(k, 0) + v in a loop | df.groupby("k")["v"].sum() |
| Top 3 | sorted(rows, key=..., reverse=True)[:3] | df.nlargest(3, "v") |
| Join two tables | build a lookup dictionary, then loop | a.merge(b, on="k") |
| Blanks | empty text "" from csv, None from JSON | NaN; use .isna() |
| Numbers | text 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
- Python cells and SQL cells sit side by side. A SQL cell's result is a dataframe. Use it in a Python cell by its name, and everything from Level 2 on works on it.
- The last line of a cell is the output. End a cell with the dataframe or number you want to show, as in the boxes on this page.
- Small cells, clear names. One step per cell, and names like
monthly_revenue, notdf2. - Practise without the AI. Hex has AI help built in. An exam may switch it off or ban it. Practise as if it is off.
- Check row counts after every merge. A
len()before and after takes seconds and catches most mistakes. - Write your assumptions down. How you handled blanks, ties and duplicates. Graders read them.
- Run everything from the top before you submit. It proves your answer does not depend on a cell you changed or deleted.
▸ 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.
Shop Which month had the highest delivered revenue (quantity times price)? Return one row:
month(YYYY-MM) andrevenuerounded to 2 decimals.Hint
Filter delivered, merge products, groupby month, sum, nlargest(1).
Show the answer
Music Each listener's favourite artist: the one they streamed most. Ties: lower
artist_id. Returnlistener_idandartist_id.Hint
Merge streams with songs, count per listener and artist, sort, groupby head(1).
Show the answer
Football Which team has the most points (3 for a win, 1 for a draw) from played matches, home and away? Return one row:
nameandpoints.Hint
Stack home and away results with pd.concat, as in step 34, then merge team names.
Show the answer
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
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
nameandaccept_pct.Hint
Merge companies, groupby name with agg(n=..., accepted=...), filter n >= 3, then divide.
Show the answer
Music Skip rate (plays under 30 seconds) for each plan, as a percentage rounded to 1 decimal. Return
planandskip_pct.Hint
Merge listeners, flag skips, groupby plan, mean of the flag times 100.
Show the answer
Shop No pandas allowed. Using
csvonly, store a dictionary of productcategoryto 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
Jobs From
offers_api.json, store a dictionary oflevelto 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
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
Jobs Remove duplicate offers (same in every column but
offer_id), then give the average base salary perindustry, rounded to 0 decimals.Hint
drop_duplicates with a subset, merge companies, groupby industry.
Show the answer
▸ Practice next
- Python from zeroEvery idea explained slowly, from installing Python to your first chart.
- SQL by exampleThe same patterns and the same data, in SQL.
- Take-home walkthroughA made-up take-home in Hex, worked end to end.
- Data tech examsThe usual question types, and 15 to practise.
- SQL and Python practiceEight take-home tasks: some SQL, then some Python.