Pandas Exercises
Time to practise! Each exercise has a starter playground that already builds the data and runs as-is, printing a placeholder so you can see the format. Replace the TODO parts, press ▶ Run, and compare with the "Expected" result. Try for a few minutes before opening the solution.
| # | Exercise | Topics |
|---|---|---|
| 1 | Library snapshot | DataFrame, shape, mean, idxmax |
| 2 | Cheap and well rated | boolean filtering, query |
| 3 | Clean the sensor log | drop_duplicates, fillna, median |
| 4 | Top orders | assign, nlargest |
| 5 | Sales per category | groupby, named aggregation |
| 6 | Join the tables | merge, groupby |
| 7 | Shift grid | pivot_table, fill_value |
| 8 | Weekly totals | to_datetime, resample |
| 9 | Email domains | .str methods, value_counts |
1. Library snapshot
Build a DataFrame from the books dictionary, then print its shape, the average number of pages (rounded to 1 decimal) and the title of the longest book.
Expected: (5, 3), then 401.2, then Middlemarch.
import pandas as pd
books = {
"title": ["Kindred", "Middlemarch", "Persuasion", "Solaris", "Beloved"],
"year": [1979, 1871, 1817, 1961, 1987],
"pages": [264, 880, 249, 204, 409],
}
df = None # TODO: build the DataFrame
print("shape?") # TODO
print("average pages?") # TODO
print("longest?") # TODOshape?
average pages?
longest?
Show solution
import pandas as pd
books = {
"title": ["Kindred", "Middlemarch", "Persuasion", "Solaris", "Beloved"],
"year": [1979, 1871, 1817, 1961, 1987],
"pages": [264, 880, 249, 204, 409],
}
df = pd.DataFrame(books)
print(df.shape)
print(round(df["pages"].mean(), 1))
print(df.loc[df["pages"].idxmax(), "title"])2. Cheap and well rated
From the apps table, keep the apps that cost less than 5 and have a rating of at least 4.3. Print only the name column as a list. Then do the same with query().
Expected: ['Notely', 'Sky Map'] twice.
import pandas as pd
apps = pd.DataFrame({
"name": ["Notely", "FitPro", "Sky Map", "Budgeto", "PhotoFix"],
"price": [0.0, 7.99, 2.99, 4.99, 1.99],
"rating": [4.6, 4.8, 4.4, 4.1, 3.9],
})
# TODO: boolean mask version
print([])
# TODO: query() version
print([])[]
[]
Show solution
import pandas as pd
apps = pd.DataFrame({
"name": ["Notely", "FitPro", "Sky Map", "Budgeto", "PhotoFix"],
"price": [0.0, 7.99, 2.99, 4.99, 1.99],
"rating": [4.6, 4.8, 4.4, 4.1, 3.9],
})
mask = (apps["price"] < 5) & (apps["rating"] >= 4.3)
print(apps.loc[mask, "name"].to_list())
print(apps.query("price < 5 and rating >= 4.3")["name"].to_list())3. Clean the sensor log
The log has one duplicated row and two missing humidity readings. Remove the duplicate, then fill missing humidity with the median of the remaining values. Print the cleaned frame.
Expected: 5 rows, and both gaps filled with 48.0.
import numpy as np
import pandas as pd
log = pd.DataFrame({
"time": ["10:00", "10:05", "10:05", "10:10", "10:15", "10:20"],
"temp": [21.0, 21.4, 21.4, 21.9, 22.3, 22.1],
"humidity": [45.0, np.nan, np.nan, 48.0, 51.0, np.nan],
})
clean = log # TODO: drop duplicates and fill humidity
print(clean) time temp humidity
0 10:00 21.0 45.0
1 10:05 21.4 NaN
2 10:05 21.4 NaN
3 10:10 21.9 48.0
4 10:15 22.3 51.0
5 10:20 22.1 NaN
Show solution
import numpy as np
import pandas as pd
log = pd.DataFrame({
"time": ["10:00", "10:05", "10:05", "10:10", "10:15", "10:20"],
"temp": [21.0, 21.4, 21.4, 21.9, 22.3, 22.1],
"humidity": [45.0, np.nan, np.nan, 48.0, 51.0, np.nan],
})
clean = log.drop_duplicates()
clean = clean.fillna({"humidity": clean["humidity"].median()})
print(clean)4. Top orders
Add a total column (qty * unit_price) with assign, and print the two orders with the largest total, showing only order and total.
Expected: orders B7 (96.0) and A3 (75.0).
import pandas as pd
orders = pd.DataFrame({
"order": ["A1", "A3", "B2", "B7", "C4"],
"qty": [2, 5, 1, 8, 3],
"unit_price": [19.5, 15.0, 42.0, 12.0, 9.9],
})
# TODO: assign a total column and pick the top 2
print(orders.head(2)) order qty unit_price
0 A1 2 19.5
1 A3 5 15.0
Show solution
import pandas as pd
orders = pd.DataFrame({
"order": ["A1", "A3", "B2", "B7", "C4"],
"qty": [2, 5, 1, 8, 3],
"unit_price": [19.5, 15.0, 42.0, 12.0, 9.9],
})
top = (orders
.assign(total=lambda d: d["qty"] * d["unit_price"])
.nlargest(2, "total")[["order", "total"]])
print(top)5. Sales per category
For each category, compute the number of sales (n_sales), the total amount (revenue) and the average amount rounded to 2 decimals (avg_sale). Sort by revenue, highest first.
Expected first row: garden with 3 sales and revenue 205.0.
import pandas as pd
sales = pd.DataFrame({
"category": ["garden", "kitchen", "garden", "toys", "kitchen", "garden", "toys"],
"amount": [80.0, 35.5, 45.0, 22.0, 64.0, 80.0, 18.5],
})
summary = sales # TODO: groupby + named aggregation
print(summary) category amount
0 garden 80.0
1 kitchen 35.5
2 garden 45.0
3 toys 22.0
4 kitchen 64.0
5 garden 80.0
6 toys 18.5
Show solution
import pandas as pd
sales = pd.DataFrame({
"category": ["garden", "kitchen", "garden", "toys", "kitchen", "garden", "toys"],
"amount": [80.0, 35.5, 45.0, 22.0, 64.0, 80.0, 18.5],
})
summary = (sales.groupby("category")
.agg(n_sales=("amount", "size"),
revenue=("amount", "sum"),
avg_sale=("amount", "mean"))
.round(2)
.sort_values("revenue", ascending=False))
print(summary)6. Join the tables
Merge lines with products on sku, compute the revenue per line (qty * price), and print the total revenue per category.
Expected: drinks 33.0 and snacks 17.0.
import pandas as pd
products = pd.DataFrame({
"sku": ["S1", "S2", "D1", "D2"],
"category": ["snacks", "snacks", "drinks", "drinks"],
"price": [2.5, 4.0, 3.0, 4.5],
})
lines = pd.DataFrame({
"sku": ["D1", "S2", "D2", "S1", "D1"],
"qty": [4, 3, 2, 2, 4],
})
# TODO: merge, compute revenue, group by category
print(lines) sku qty
0 D1 4
1 S2 3
2 D2 2
3 S1 2
4 D1 4
Show solution
import pandas as pd
products = pd.DataFrame({
"sku": ["S1", "S2", "D1", "D2"],
"category": ["snacks", "snacks", "drinks", "drinks"],
"price": [2.5, 4.0, 3.0, 4.5],
})
lines = pd.DataFrame({
"sku": ["D1", "S2", "D2", "S1", "D1"],
"qty": [4, 3, 2, 2, 4],
})
merged = lines.merge(products, on="sku", how="left")
merged["revenue"] = merged["qty"] * merged["price"]
print(merged.groupby("category")["revenue"].sum())7. Shift grid
Build a grid with one row per nurse, one column per shift (early, late, night), and the number of shifts worked in each cell. Empty combinations should show 0.
Expected: Kai has 0 night shifts and Rosa has 2 early shifts.
import pandas as pd
rota = pd.DataFrame({
"nurse": ["Rosa", "Kai", "Rosa", "Lena", "Kai", "Lena", "Rosa", "Kai"],
"shift": ["early", "late", "early", "night", "early", "night", "night", "late"],
})
grid = rota # TODO: pivot_table (or crosstab)
print(grid) nurse shift
0 Rosa early
1 Kai late
2 Rosa early
3 Lena night
4 Kai early
5 Lena night
6 Rosa night
7 Kai late
Show solution
import pandas as pd
rota = pd.DataFrame({
"nurse": ["Rosa", "Kai", "Rosa", "Lena", "Kai", "Lena", "Rosa", "Kai"],
"shift": ["early", "late", "early", "night", "early", "night", "night", "late"],
})
grid = rota.pivot_table(index="nurse", columns="shift", aggfunc="size", fill_value=0)
print(grid)
# pd.crosstab(rota["nurse"], rota["shift"]) gives the same counts8. Weekly totals
Convert the date column to datetimes and compute the total km cycled per week (weeks ending on Sunday).
Expected: three weeks with totals 47, 30 and 55.
import pandas as pd
rides = pd.DataFrame({
"date": ["2024-04-01", "2024-04-03", "2024-04-06", "2024-04-09",
"2024-04-12", "2024-04-15", "2024-04-17", "2024-04-21"],
"km": [12, 20, 15, 18, 12, 25, 10, 20],
})
# TODO: to_datetime, then resample("W", on="date")
print(rides["km"].sum())132
Show solution
import pandas as pd
rides = pd.DataFrame({
"date": ["2024-04-01", "2024-04-03", "2024-04-06", "2024-04-09",
"2024-04-12", "2024-04-15", "2024-04-17", "2024-04-21"],
"km": [12, 20, 15, 18, 12, 25, 10, 20],
})
rides["date"] = pd.to_datetime(rides["date"])
print(rides.resample("W", on="date")["km"].sum())9. Email domains
Extract the domain (the part after @) from each email, lower-cased, and count how many users each domain has.
Expected: mail.com 3, uni.edu 2, corp.io 1.
import pandas as pd
users = pd.Series(["ann@Mail.com", "bo@uni.edu", "cy@mail.com",
"di@corp.io", "ed@MAIL.COM", "fi@uni.edu"])
domains = users # TODO: split or extract, then lower()
print(domains.value_counts())ann@Mail.com 1
bo@uni.edu 1
cy@mail.com 1
di@corp.io 1
ed@MAIL.COM 1
fi@uni.edu 1
Name: count, dtype: int64
Show solution
import pandas as pd
users = pd.Series(["ann@Mail.com", "bo@uni.edu", "cy@mail.com",
"di@corp.io", "ed@MAIL.COM", "fi@uni.edu"])
domains = users.str.split("@").str[1].str.lower()
print(domains.value_counts())Test yourself
Which line keeps rows where price < 5 and rating >= 4.3?
- df[df.price < 5 and df.rating >= 4.3]
- df[(df["price"] < 5) & (df["rating"] >= 4.3)]
- df.filter(price < 5, rating >= 4.3)
- df.where(price < 5)
Which method counts rows per group, including rows with missing values?
- count()
- size()
- nunique()
- sum()