Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 64 ยท Practice and Review

Practice Exercises with Solutions

25 graded pandas exercises with solutions on selecting, grouping, merging, time series and data cleaning. Practice in your browser with ready-made data.

Reading about pandas and writing pandas are different skills, and only practice builds the second one. This page has 25 exercises in five groups, ordered from beginner to advanced inside each group: selecting and filtering, grouping, merging, time series, and cleaning. Every group starts with an editor that already contains the data, so you can focus on the question.

Here is how to get the most out of them:

  • Try first, peek later. Spend a few minutes on each exercise before opening the solution. Being stuck for a while is where the learning happens.
  • Check the shape of your answer. Each exercise says what the result should look like, so you can compare without looking at the code.
  • Compare, don't copy. pandas often has several correct ways to do the same thing. Read our solution for ideas, then improve your own.

The solutions use the same variable names as the editor in their group, so you can paste a solution under the data to run it. Keep the cheat sheet open in another tab if you need a reminder.

flowchart LR
    A["Read the task"] --> B["Predict the shape<br/>of the answer"]
    B --> C["Write it in the editor"]
    C --> D{"Matches the<br/>expected result?"}
    D -- "yes" --> E["Open the solution<br/>and compare ideas"]
    D -- "no" --> F["Print intermediate steps"]
    F --> C

A good practice loop: predict the result, run it, debug by printing intermediate steps, and only then read the solution.

Group 1: selecting and filtering

These practice columns and rows, loc and iloc, boolean filtering and sorting. The editor holds a small staff table.

Python Group 1 workspace: staff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

1. Two columns, three rows (Beginner)

Show only the name and salary columns of the first three people. Expected:

TEXT
   name  salary
0   Ana   98000
1   Ben   91000
2  Chen  105000
Show solution
Python
print(staff[["name", "salary"]].head(3))

A list inside the brackets selects several columns and returns a DataFrame; head(3) keeps the first three rows.

2. Well-paid engineers (Beginner)

Find the name and salary of everyone in the Eng department who earns more than 90,000. Expected: Ana (98000), Ben (91000) and Chen (105000).

Show solution
Python
mask = (staff["dept"] == "Eng") & (staff["salary"] > 90000)
print(staff.loc[mask, ["name", "salary"]])

Each comparison needs its own parentheses, and you combine masks with &, not and. loc takes the mask for rows and a list of column labels in one step. See Filtering with Conditions.

3. By position (Intermediate)

Using positions only, select the third to fifth rows and the first three columns. Expected: the rows for Chen, Dara and Eli, with columns name, dept and role.

Show solution
Python
print(staff.iloc[2:5, :3])

iloc counts from 0 and its slices exclude the end, so 2:5 gives positions 2, 3 and 4. With loc, label slices would include the end instead.

4. Remote support and sales (Intermediate)

Return a plain Python list with the names of remote employees who work in Sales or Support. Expected: ['Fay', 'Gus', 'Jo'].

Show solution
Python
mask = staff["dept"].isin(["Sales", "Support"]) & staff["remote"]
print(staff.loc[mask, "name"].tolist())

isin replaces a chain of == and |. The remote column is already boolean, so it works directly as a mask.

5. Sort and rank (Intermediate)

Sort by dept (A to Z) and, inside each department, by salary from high to low; show the first four rows of dept, name and salary. Then print the top three earners with nlargest. Expected for the first part: Design/Hana, then Eng with Chen, Ana, Ben.

Show solution
Python
ordered = staff.sort_values(["dept", "salary"], ascending=[True, False])
print(ordered[["dept", "name", "salary"]].head(4).to_string(index=False))
print(staff.nlargest(3, "salary")[["name", "salary"]].to_string(index=False))

ascending takes one flag per sort key. nlargest(3, "salary") is shorter and faster than sorting everything when you only need the top rows.

Group 2: grouping and summarizing

These practice groupby, agg and transform and pivot tables. The editor holds a sales table with a computed revenue column.

Python Group 2 workspace: sales

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

6. Revenue per region (Beginner)

Compute the total revenue for each region. Expected: East 6750, North 7740, South 5285, West 5400.

Show solution
Python
print(sales.groupby("region")["revenue"].sum())

Choose the key, pick the column, apply the aggregation: the split-apply-combine pattern in one line.

7. Named aggregation (Intermediate)

For each product, compute the average number of units (avg_units) and the highest price (max_price), rounded to one decimal. Expected: Laptop 4.2 and 900, Monitor 11.7 and 220, Mouse 36.2 and 15.

Show solution
Python
summary = sales.groupby("product").agg(
    avg_units=("units", "mean"),
    max_price=("price", "max"),
).round(1)
print(summary)

Named aggregation (new_name=(column, function)) gives clear column names and avoids a MultiIndex in the columns.

8. Share of the region (Intermediate)

Add a share column with each row's revenue divided by the total revenue of its region, rounded to three decimals. The North/Laptop row should be 0.581, and the shares inside each region add up to 1.

Show solution
Python
region_total = sales.groupby("region")["revenue"].transform("sum")
sales["share"] = (sales["revenue"] / region_total).round(3)
print(sales[["region", "product", "revenue", "share"]].head(6))
print(sales.groupby("region")["share"].sum().round(2).tolist())

transform("sum") returns a result with the same length as the original table (each row gets its group's total), so it divides cleanly. agg would have returned one row per region.

9. Region by product table (Intermediate)

Build a table with regions as rows, products as columns and the sum of units as values. Show 0 instead of missing cells and add totals. Expected last row All: Laptop 17, Monitor 35, Mouse 145, All 197.

Show solution
Python
table = sales.pivot_table(
    index="region", columns="product", values="units",
    aggfunc="sum", fill_value=0, margins=True,
)
print(table)

East sells no monitors, so fill_value=0 replaces the missing cell. margins=True adds the row and column called All.

10. Big regions and best products (Advanced)

First list the regions whose total revenue is above 6,000. Then show, for every region, the product that earned the most revenue. Expected: ['East', 'North']; best products are Laptop for East, North and South, and Monitor for West.

Show solution
Python
totals = sales.groupby("region")["revenue"].sum()
print(totals[totals > 6000].index.tolist())

best = sales.loc[sales.groupby("region")["revenue"].idxmax(), ["region", "product", "revenue"]]
print(best.to_string(index=False))

idxmax inside a groupby returns the index label of the largest value in each group, and loc uses those labels to fetch the full rows. This works because the index labels of sales are unique.

Group 3: combining tables

These practice concat and merge. The editor holds small customers, orders, jan and feb tables.

Python Group 3 workspace: customers and orders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

11. Orders with customer details (Beginner)

Attach each customer's name and city to the orders. The key has different names in the two tables (cust and customer_id). How many rows does an inner merge keep? Expected: 4, because order 105 belongs to an unknown customer.

Show solution
Python
merged = orders.merge(customers, left_on="cust", right_on="customer_id", how="inner")
print(merged)
print(len(merged))

left_on and right_on name the key in each table. An inner merge keeps only keys found on both sides, so order 105 disappears silently, which is why you should always compare row counts.

12. Customers who never ordered (Intermediate)

List the names of customers who have no orders. Expected: ['Bo', 'Di'].

Show solution
Python
check = customers.merge(orders, left_on="customer_id", right_on="cust", how="left", indicator=True)
print(check.loc[check["_merge"] == "left_only", "name"].tolist())

A left merge keeps every customer; indicator=True adds a _merge column that says where each row came from. Rows marked left_only have no match, an "anti-join".

13. Stack two months (Intermediate)

Combine jan and feb into one table with a month column (jan or feb), then compute the total sold per sku. Expected totals: A 17, B 4, C 9.

Show solution
Python
both = (
    pd.concat([jan, feb], keys=["jan", "feb"], names=["month"])
    .reset_index(level="month")
    .reset_index(drop=True)
)
print(both)
print(both.groupby("sku")["sold"].sum())

keys= labels each piece in a new index level; reset_index(level="month") turns that level into a normal column. A final reset_index(drop=True) discards the leftover row numbers.

14. Old and new prices (Intermediate)

You have two price lists, one with SKUs A, B, C and one with A, B, D. Combine them so that every SKU appears once, with columns price_old and price_new. Expected: A has 5 and 6, B has 7 and 7, C has only an old price, D has only a new price.

Show solution
Python
prices_a = pd.DataFrame({"sku": ["A", "B", "C"], "price": [5, 7, 9]})
prices_b = pd.DataFrame({"sku": ["A", "B", "D"], "price": [6, 7, 3]})

both = prices_a.merge(prices_b, on="sku", how="outer", suffixes=("_old", "_new"))
print(both)

Both tables have a price column, so suffixes keeps them apart. An outer merge keeps keys from either side and fills the gaps with NaN.

15. The duplicate-key trap (Advanced)

A tiers table lists customer 1 twice (gold and silver). Merge orders with it on the customer key, once without any checks and once with validate="many_to_one". How many rows does the unchecked left merge produce, and what happens with validate? Expected: 7 rows (the two orders of customer 1 are duplicated), and a MergeError.

Show solution
Python
tiers = pd.DataFrame({"customer_id": [1, 1, 2], "tier": ["gold", "silver", "basic"]})

unchecked = orders.merge(tiers, left_on="cust", right_on="customer_id", how="left")
print(len(orders), "->", len(unchecked))

try:
    orders.merge(tiers, left_on="cust", right_on="customer_id", validate="many_to_one")
except Exception as error:
    print(type(error).__name__)

Duplicate keys on the right multiply the matching left rows, which would inflate any later sums. validate turns this silent bug into an immediate error.

Group 4: time series

These practice dates and times, time series basics, resampling and rolling windows. The editor creates 28 days of website visits with dates stored as text such as 01/03/2025.

Python Group 4 workspace: daily visits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

16. Real dates (Beginner)

Convert the day column to datetime (the format is day/month/year), then print the weekday names of the first three rows. Expected: ['Saturday', 'Sunday', 'Monday'].

Show solution
Python
visits["day"] = pd.to_datetime(visits["day"], format="%d/%m/%Y")
print(visits["day"].dt.day_name().head(3).tolist())

Without format=, 01/03/2025 could be read as January 3 or March 1. Giving the format removes the guess and speeds up parsing.

17. Slice by date (Intermediate)

Make day the index and select the visits from 10 March to 12 March (both days included), and the single value for 3 March. Expected: 220, 239, 250, and then 190.

Show solution
Python
visits["day"] = pd.to_datetime(visits["day"], format="%d/%m/%Y")
ts = visits.set_index("day")["visits"]
print(ts["2025-03-10":"2025-03-12"])
print(ts.loc["2025-03-03"])

On a DatetimeIndex, string slices are inclusive at both ends and accept ISO dates.

18. Weekly totals (Intermediate)

Compute the sum of visits per week, with weeks ending on Sunday. Expected: 398, 1535, 1748, 2050 and 1630, for the weeks ending 2 March to 30 March. The first week has only two days.

Show solution
Python
visits["day"] = pd.to_datetime(visits["day"], format="%d/%m/%Y")
ts = visits.set_index("day")["visits"]
print(ts.resample("W").sum())

resample is groupby for time: "W" means weeks ending on Sunday, and the label is the last day of each period.

19. A smoother line (Intermediate)

Compute a 7-day rolling mean of the visits and show its first three non-missing values, rounded to one decimal. Expected: 211.7, 214.7 and 219.3, starting on 7 March.

Show solution
Python
visits["day"] = pd.to_datetime(visits["day"], format="%d/%m/%Y")
ts = visits.set_index("day")["visits"]
print(ts.rolling(7).mean().dropna().round(1).head(3))

A window of 7 needs 7 values, so the first six results are NaN. Use min_periods if you want partial windows.

20. The biggest jump (Advanced)

On which day did visits grow the most compared with the previous day, and by how much? Also print the day-over-day change in percent for the second and third day, rounded to one decimal. Expected: 6 March with +43, and -17.4 and 5.6.

Show solution
Python
visits["day"] = pd.to_datetime(visits["day"], format="%d/%m/%Y")
ts = visits.set_index("day")["visits"]

change = ts.diff()
print(change.idxmax().date(), change.max())
print(ts.pct_change().mul(100).round(1).iloc[1:3].tolist())

diff() subtracts the previous row, and idxmax() returns the index label, which here is a date. pct_change() returns fractions, so multiply by 100 for percent.

Group 5: cleaning

These practice text, data types, missing data and duplicates. The editor reads a small messy CSV into raw. The exercises build on each other, so keep going in one editor: each solution continues with clean.

Python Group 5 workspace: messy data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

21. Tidy headers and categories (Beginner)

Create clean from raw with column names in snake_case (no spaces, lowercase, no stray whitespace), and standardize city so that London appears 3 times and Paris twice. Expected columns: full_name, city, price, qty, updated.

Show solution
Python
clean = raw.rename(columns=lambda name: name.strip().lower().replace(" ", "_"))
clean["city"] = clean["city"].str.strip().str.title()
print(list(clean.columns))
print(clean["city"].value_counts())

rename accepts a function that is applied to every column name. .str.strip().str.title() fixes whitespace and capitalization in one chain.

22. Prices as numbers (Intermediate)

price is read as text because it mixes "$1,200" with plain numbers such as 950 (the n/a is already read as missing). Turn it into floats, with NaN where there is no number. Expected: [1200.0, 950.0, nan, 980.0, 1050.0] with dtype float64.

Show solution
Python
text = clean["price"].str.replace(r"[$,]", "", regex=True)
clean["price"] = pd.to_numeric(text, errors="coerce")
print(clean["price"].tolist(), clean["price"].dtype)

Remove the currency symbol and thousands separator with a regular expression, then to_numeric(errors="coerce") converts what it can and turns anything unparseable into NaN instead of raising an error. Here it would also protect you from a stray value like "call us".

23. Fill gaps sensibly (Intermediate)

One qty is missing. Fill missing quantities with the median qty of the same city. Expected: [3.0, 3.5, 2.0, 4.0, 1.0], so London's gap becomes 3.5.

Show solution
Python
city_median = clean.groupby("city")["qty"].transform("median")
clean["qty"] = clean["qty"].fillna(city_median)
print(clean["qty"].tolist())

fillna accepts a Series and fills each gap from the value with the same index label. transform("median") produced a full-length Series of per-city medians, which is exactly what is needed.

24. Keep the latest record (Intermediate)

Grace Hopper appears twice. Convert updated to datetime, standardize full_name with .str.strip().str.title(), and keep only the most recent row per person. Expected: 4 rows, and Grace's price is 980.0, from 2025-02-01.

Show solution
Python
clean["updated"] = pd.to_datetime(clean["updated"])
clean["full_name"] = clean["full_name"].str.strip().str.title()

latest = clean.sort_values("updated").drop_duplicates("full_name", keep="last")
print(latest[["full_name", "price", "updated"]].to_string(index=False))

drop_duplicates keeps the first or last row it meets, so sort by the timestamp first and use keep="last". Without cleaning the names, "ada lovelace" and "Ada Lovelace" would count as different people.

25. Split names (Advanced)

From latest, build a DataFrame with columns first and last by splitting full_name at the first space. Keep the original index. Expected: Alan Turing, Ada Lovelace, Linus Torvalds and Grace Hopper.

Show solution
Python
names = latest["full_name"].str.split(" ", n=1, expand=True)
names.columns = ["first", "last"]
print(names)

expand=True returns a DataFrame with one column per piece, and n=1 limits the split to one cut, so a name such as "Mary Jane Watson" would become Mary and Jane Watson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tool gives every row the total of its group, so you can compute shares?

    transform returns a result aligned with the original rows, so each row receives its own group's total. agg returns one row per group.
  2. 2. What does iloc[2:5] select?

    iloc works by position and, like normal Python slices, excludes the end. Positions 2, 3 and 4 are returned.
  3. 3. How can you find rows in the left table that have no match in the right table?

    An inner merge discards the unmatched rows, while a left merge with indicator=True keeps them and labels where each row came from.
  4. 4. Why use errors='coerce' with pd.to_numeric on a messy column?

    With the default errors='raise', one bad value stops the conversion. coerce marks it as missing, so you can count and handle the problem rows afterwards.

Summary

  • Selection: loc uses labels and masks, iloc uses positions (end excluded), and masks need parentheses and & / |.
  • Grouping: agg shrinks groups to one row, transform keeps the original length, and pivot_table is a groupby shown as a grid.
  • Merging: check row counts before and after, use indicator=True to find unmatched rows and validate= to catch duplicate keys.
  • Time series: parse dates with an explicit format, put them in the index, then slice, resample and rolling.
  • Cleaning: standardize text first, convert with to_numeric(errors="coerce"), fill gaps with group statistics, and sort before drop_duplicates(keep="last").

Next, rehearse explaining these ideas out loud with pandas Interview Questions.