Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Practice: Ten Polars Exercises with Solutions

Ten hands-on Polars exercises with runnable solutions covering select, filter, new columns, strings, dates, group_by, joins, window functions, pivot and null handling.

The fastest way to learn Polars is to write queries. Here are ten exercises that follow the course from simple to demanding. Each one gives you a task and a small data set; try to solve it yourself first, using the editor below the task (it already holds the data, so just add your query at the bottom and press Run). Then compare with the solution that follows.

All exercises use the same table, a small staff list. Copy this setup block into any editor to experiment:

Python
import polars as pl
from datetime import date

staff = pl.DataFrame({
    "name": ["Ana", "Ben", "Cleo", "Dev", "Eli", "Fay", "Gus", "Hana"],
    "team": ["data", "data", "web", "web", "web", "ops", "ops", "data"],
    "salary": [82000, 74000, 68000, 71000, None, 59000, 62000, 91000],
    "hired": [date(2019, 3, 1), date(2021, 7, 15), date(2020, 1, 20), date(2022, 11, 2),
              date(2018, 5, 30), date(2023, 2, 14), date(2017, 9, 9), date(2016, 6, 1)],
    "email": [" [email protected]", "[email protected] ", "[email protected]", "[email protected]",
              "[email protected]", "[email protected]", "[email protected]", "[email protected]"],
})

Exercise 1: select and filter

Task: Show the name and salary of everyone who earns more than 70,000, highest salary first.

Python Exercise 1: editor and solution

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.

Eli (salary null) is not in the output. A comparison with null is null, and filter keeps only rows that are true. That is the rule to remember when your results look one row short.

Exercise 2: a derived column

Task: Add a column band with "senior" for salaries of at least 80,000, "mid" for 65,000 to 79,999, "junior" for anything lower, and "unknown" when the salary is missing.

Python Exercise 2: solution

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.

The null check comes first, because a null salary would otherwise fall through every comparison and land in otherwise as "junior". Order matters in a when/then chain.

Exercise 3: clean text

Task: The emails have stray spaces and inconsistent case. Produce a clean lowercase email column and a domain column containing only the part after the @.

Python Exercise 3: solution

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.

The second with_columns is a separate call because it needs the cleaned email; expressions in the same call cannot see each other's results. str.split gives a list; list.last() takes the final element. An alternative is str.extract(r"@(.+)$", 1).

Exercise 4: dates

Task: Add years (whole years of service as of 2025-01-01) and hire_month (the month name). Then keep only people hired in the first half of a year.

Python Exercise 4: solution

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.

Date minus date gives a Duration; dt.total_days() converts it to a number. Dividing by 365.25 is a quick approximation of years; for exact calendar differences you would compare year, month and day parts.

Exercise 5: group and aggregate

Task: For each team, report the head count, the average salary (ignoring missing values, rounded to whole numbers), and the name of the person hired first.

Python Exercise 5: solution

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.

sort_by("hired") sorts the names by another column inside the group and .first() takes the earliest. This pattern, "the value of column A where column B is smallest", comes up constantly.

Exercise 6: window functions

Task: Add each person's salary as a percentage of their team's total salary, and their rank inside the team (1 = highest salary). Missing salaries should stay missing.

Python Exercise 6: solution

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.

sum() ignores the null when totalling, so the web team's percentages add up to 100 over the two known salaries. The rank of a null is null as well.

Exercise 7: a join

Task: Join the staff to this table of team budgets, and list teams whose average salary is above their budget_per_head. Also list teams that have a budget but no staff.

Python Exercise 7: solution

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.

The anti join answers "what is in this table but not in that one?" without any null checking, and always returns only the left table's columns.

Exercise 8: pivot

Task: Make a table with one row per team and one column per hiring year since 2019, counting how many people were hired.

Python Exercise 8: solution

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.

Pivoting creates column names from the year values, as text ("2019", and so on). fill_null(0) turns "no one hired" into a zero count, and the explicit select puts the year columns in order.

Exercise 9: missing data

Task: Replace the missing salary with the median salary of that person's team; if the whole team is missing, use the overall median. Report how many values you filled.

Python Exercise 9: solution

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.

Two fill_null calls give a clear priority order: the team median first, then the global median as a fallback. Keep the original column next to the filled one so you can always tell what was estimated.

Exercise 10: a final, lazy query

Task: Write one lazy query that reports, for teams with at least two known salaries, the team, the spread (max minus min) and the highest earner's name, sorted by spread, and print its optimized plan.

Python Exercise 10: solution

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.

Dropping the null salaries first means the count n is the number of known salaries, which is what the question asks for. In the plan, check which operations the optimizer moved and which columns the source reports.

How did you do?

  • 0 to 4 solved without peeking: re-read the lessons on expressions and group_by, then try again tomorrow.
  • 5 to 8: you have the core; review the places where you got stuck, usually null handling and the order of when/then branches.
  • 9 to 10: continue with harder practice questions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does filter(pl.col('salary') > 70000) drop rows with a null salary?

    null > 70000 is null (unknown), and filter keeps only true rows.
  2. 2. In a when/then chain, why is the is_null check placed first?

    Branches are tested top to bottom; handling null first prevents it falling through to the default.
  3. 3. Which join answers 'which budget teams have no staff?'

    An anti join keeps left rows with no match on the right.
  4. 4. How do you compute each row's share of its group total?

    over('group') broadcasts the group total to each row, so a division gives the share.

Summary

  • Comparisons with null give null; filter drops them. Handle nulls explicitly and early.
  • when/then/otherwise chains are ordered; the first true branch wins.
  • Chain with_columns calls when a later expression needs an earlier result.
  • group_by().agg() can also pick "the value where another column is smallest" with sort_by(...).first().
  • over gives shares and ranks; anti joins find missing keys; pivot creates text-named columns.

Next: Harder Practice Questions