31. Polars
Modules 24 and 25 analyzed the course tables with pandas. Module 30 asked the same questions in SQL. This module answers them a third way, with Polars: a DataFrame library that runs on all CPU cores, checks types strictly and can optimize a whole query before it reads a single row. Polars code reads like a list of column formulas. Once you know its few building blocks, you can write most analyses in fewer lines than in pandas, and they often run several times faster.
This module uses Polars 2. Many tutorials online still show Polars 0.x or 1.x names (groupby, melt, with_row_count, pl.count()). They fail or warn in Polars 2. Every block on this page runs with the installed version.
What you will learn
Section titled “What you will learn”- Build a
Seriesand aDataFrame, read a Polars schema, and read CSV and Parquet files with the right dtypes. - Write expressions with
pl.col()and run them in the contextsselect,with_columns,filterandgroup_by().agg(). - Add conditional columns with
when/then/otherwise, text and date columns with the.strand.dtnamespaces, and window columns withover. - Build lazy queries with
scan_csvandscan_parquet, read the optimized plan withexplain()and run it withcollect(). - Join tables with inner, left, full, semi and anti joins, reshape them with
pivotandunpivot, and make the row order of every result deterministic. - Translate pandas code to Polars, convert data between the two, and choose pandas, Polars or SQL with DuckDB for a task.
Prerequisites
Section titled “Prerequisites”- 24. pandas fundamentals: DataFrame, Series, dtypes, filtering and new columns.
- 25. pandas advanced: groupby, merge, pivot tables, melt and window functions.
- 30. SQL for data analysis: GROUP BY, JOINs, window functions and DuckDB.
- 10. Iterators and generators: lazy pipelines that run only when you ask for the result.
- The course datasets in a
data/folder: Get the data. Polars, pandas, pyarrow and DuckDB come with the course environment.
Concepts
Section titled “Concepts”What Polars is
Section titled “What Polars is”Polars is a DataFrame library written in Rust, a compiled language that is about as fast as C. You use it from Python with import polars as pl. It stores each column in the Apache Arrow columnar format that module 24 introduced, so a column is one contiguous block of memory.
Four design choices make Polars different from pandas:
- No index. A Polars DataFrame has no row labels. A row is identified only by its position or by the values in its columns. There is no
loc, noreset_index()and no index alignment to surprise you. - Expressions. You describe each column as a formula, such as
pl.col("revenue") * 0.9. Polars runs the formulas in parallel, on all CPU cores. - A lazy API with an optimizer. You can describe a whole query first and run it later. Before it runs, Polars rewrites the query to read fewer columns and rows.
- Strict types. Each column has exactly one dtype. Polars raises an error instead of silently turning numbers into text or integers into floats.
| pandas | Polars | |
|---|---|---|
| Row labels | an index on every DataFrame | none; rows have positions only |
| Missing value | NaN, NaT or pd.NA, depending on the dtype |
null in every dtype |
| Main style | many methods on the DataFrame and on df["col"] |
a few contexts that take expressions |
| Execution | eager: each line runs at once | eager, or lazy with a query optimizer |
| CPU cores | mostly one | all of them by default |
| Type rules | flexible, with silent conversions | strict; a wrong type raises an error |
| Ecosystem | the standard input of scikit-learn, statsmodels, seaborn | converts to pandas or NumPy in one call |
Setup: display options
Section titled “Setup: display options”Polars prints a DataFrame as a box-drawn table. Its defaults depend on the terminal, so the course fixes them in a setup block at the top of every Polars page. This keeps every printed table stable and at most 100 characters wide.
import polars as pl
pl.Config.set_tbl_rows(10)pl.Config.set_tbl_cols(8)pl.Config.set_tbl_width_chars(100)pl.Config.set_fmt_str_lengths(30)pl.Config.set_fmt_float("full")| Setting | Effect |
|---|---|
set_tbl_rows(10) |
Show at most 10 rows. A longer table shows its first and last 5 rows with a … row between them. |
set_tbl_cols(8) |
Show at most 8 columns. A wider table shows the first 4 and the last 4 with a … column. |
set_tbl_width_chars(100) |
Never draw a table wider than 100 characters. Long cells wrap onto a second line. |
set_fmt_str_lengths(30) |
Show up to 30 characters of a text cell, so product names are not cut. |
set_fmt_float("full") |
Print every digit of a float. The default switches large values to scientific notation (3.5965e6), which hides the cents. Round the floats you print. |
pl.Config is global for the Python process. For one table only, use it as a context manager: with pl.Config(tbl_rows=20): print(df).
Series and DataFrame
Section titled “Series and DataFrame”A Polars Series is one named column with one dtype. A Polars DataFrame is a set of Series of equal length. These are the same ideas as in pandas, without the index.
revenue = pl.Series("revenue", [66.49, 14.99, None, 224.1])print(revenue)print(revenue.dtype, revenue.len(), revenue.null_count())print(revenue.mean())shape: (4,)Series: 'revenue' [f64][ 66.49 14.99 null 224.1]Float64 4 1101.86None becomes null, the Polars marker for a missing value. Every dtype can hold null, so an integer column with a gap stays an integer column. Aggregations such as mean() skip nulls: the mean is (66.49 + 14.99 + 224.1) / 3.
A DataFrame is often built from a dict of lists, one list per column:
orders = pl.DataFrame( { "order_id": ["O000001", "O000002", "O000004", "O000004"], "store_id": ["S11", "S10", "S11", "S11"], "quantity": [1, 1, 1, 1], "revenue": [66.49, 14.99, 59.99, 224.1], })print(orders)print(orders.shape, orders.height, orders.width)print(orders.columns)shape: (4, 4)┌──────────┬──────────┬──────────┬─────────┐│ order_id ┆ store_id ┆ quantity ┆ revenue ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ str ┆ i64 ┆ f64 │╞══════════╪══════════╪══════════╪═════════╡│ O000001 ┆ S11 ┆ 1 ┆ 66.49 ││ O000002 ┆ S10 ┆ 1 ┆ 14.99 ││ O000004 ┆ S11 ┆ 1 ┆ 59.99 ││ O000004 ┆ S11 ┆ 1 ┆ 224.1 │└──────────┴──────────┴──────────┴─────────┘(4, 4) 4 4['order_id', 'store_id', 'quantity', 'revenue']The header shows each column’s name and dtype: str is text, i64 a 64-bit integer, f64 a 64-bit float. height is the number of rows and width the number of columns. The schema is the ordered mapping from column name to dtype. Polars checks it before every operation.
print(orders.schema)print(orders["revenue"].sum())print(orders.select(pl.col("revenue").max()).item())Schema({'order_id': String, 'store_id': String, 'quantity': Int64, 'revenue': Float64})365.57224.1orders["revenue"] returns the column as a Series. item() takes the single value out of a 1 × 1 DataFrame, which is how you turn a result table into a Python number. The common dtypes:
| Dtype | Holds | Example column |
|---|---|---|
pl.String (str) |
UTF-8 text | product, order_id |
pl.Int64 (i64), pl.Int32, pl.UInt32 (u32) |
whole numbers | quantity; counts that Polars computes are u32 |
pl.Float64 (f64) |
decimal numbers | revenue, unit_price |
pl.Boolean (bool) |
true / false |
the result of a comparison |
pl.Date (date), pl.Datetime |
calendar dates, timestamps | order_date |
pl.Categorical, pl.Enum |
text with few distinct values | region, channel |
pl.List, pl.Struct |
a list or a record in each cell | the words of a product name |
Strict types show at construction time. A list that mixes numbers and text is an error, not a column of objects:
prices = pl.Series("unit_price", [79.99, "n/a", 249.0])TypeError: unexpected value while building Series of type Float64; found value of type String: "n/a"pandas would make an object column here and fail later, in some calculation. Polars fails at the line that caused the problem.
Reading CSV and Parquet
Section titled “Reading CSV and Parquet”pl.read_csv() reads a whole file into a DataFrame. Polars infers each dtype (works it out) from the first 100 rows. Dates stay text unless you pass try_parse_dates=True, which turns columns that look like ISO dates (2023-01-01) into the Date dtype.
sales = pl.read_csv("data/sales.csv", try_parse_dates=True)stores = pl.read_csv("data/stores.csv", try_parse_dates=True)products = pl.read_csv("data/products.csv", try_parse_dates=True)print(sales.shape, stores.shape, products.shape)for name, dtype in sales.schema.items(): print(f"{name:<12} {dtype}")(20228, 13) (12, 5) (30, 6)order_id Stringorder_date Datecustomer_id Stringstore_id Stringregion Stringchannel Stringproduct_id Stringproduct Stringcategory Stringunit_price Float64quantity Int64discount Float64revenue Float64Every column has the dtype the data dictionary promises. Three read_csv options fix most other files:
| Option | Use |
|---|---|
schema_overrides={"store_id": pl.String} |
force a dtype for some columns (zip codes, ids with leading zeros) |
null_values=["", "N/A", "-"] |
read these tokens as null |
columns=["order_date", "revenue"] |
read only some columns |
Parquet files store the schema with the data, so nothing needs to be inferred. pl.read_parquet() returns the exact dtypes that were written:
sample = pl.read_parquet("data/sales_sample.parquet")print(sample.shape)print(sample.schema["order_date"])print(sample.select(first=pl.col("order_date").min(), last=pl.col("order_date").max()))(500, 13)Datetime(time_unit='us', time_zone=None)shape: (1, 2)┌─────────────────────┬─────────────────────┐│ first ┆ last ││ --- ┆ --- ││ datetime[μs] ┆ datetime[μs] │╞═════════════════════╪═════════════════════╡│ 2023-01-01 00:00:00 ┆ 2023-01-28 00:00:00 │└─────────────────────┴─────────────────────┘The Parquet sample stores order_date as a timestamp: Datetime with microsecond (us) precision. Writing works the same way in reverse: df.write_parquet("output/sales.parquet") and df.write_csv("output/sales.csv"). The read_* functions are eager: they load the whole file now. The scan_* functions are lazy; the lazy API section below explains them.
Expressions and contexts
Section titled “Expressions and contexts”An expression is a recipe for a column. pl.col("revenue") * 0.9 means “take the column revenue and multiply each value by 0.9”. Building an expression computes nothing. It needs data first:
net = pl.col("revenue") * 0.9print(net)print(type(net).__name__)[(col("revenue")) * (dyn float: 0.9)]ExprA context is a DataFrame method that takes expressions and runs them on its data. Four contexts cover most work:
| Context | Returns | pandas equivalent |
|---|---|---|
df.select(exprs) |
only the columns the expressions produce | df[["a", "b"]], new columns |
df.with_columns(exprs) |
all old columns plus new or replaced ones | df.assign(...) |
df.filter(predicate) |
the rows where the expression is true |
df[mask], df.query(...) |
df.group_by(keys).agg(exprs) |
one row per group | df.groupby(keys).agg(...) |
flowchart LR
E["Expressions<br/>pl.col('revenue') * 0.9"] --> C["Context<br/>select / with_columns<br/>filter / group_by().agg"]
D["DataFrame"] --> C
C --> R["New DataFrame"]
select keeps only what you ask for. Name a new column with .alias() or with a keyword argument:
print( sales.select( "order_id", pl.col("revenue"), (pl.col("unit_price") * pl.col("quantity")).alias("gross"), discount_pct=pl.col("discount") * 100, ).head(3))shape: (3, 4)┌──────────┬─────────┬───────┬──────────────┐│ order_id ┆ revenue ┆ gross ┆ discount_pct ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ f64 ┆ f64 ┆ f64 │╞══════════╪═════════╪═══════╪══════════════╡│ O000001 ┆ 66.49 ┆ 69.99 ┆ 5 ││ O000002 ┆ 14.99 ┆ 14.99 ┆ 0 ││ O000003 ┆ 19.99 ┆ 19.99 ┆ 0 │└──────────┴─────────┴───────┴──────────────┘A plain string such as "order_id" is short for pl.col("order_id"). with_columns keeps every column and adds the new ones at the end. A new column with an existing name replaces the old one:
lines = sales.with_columns( gross=pl.col("unit_price") * pl.col("quantity"), is_online=pl.col("channel") == "online",)print(lines.width, lines.columns[-2:])print(lines.select("gross", "revenue", "is_online").head(3))15 ['gross', 'is_online']shape: (3, 3)┌───────┬─────────┬───────────┐│ gross ┆ revenue ┆ is_online ││ --- ┆ --- ┆ --- ││ f64 ┆ f64 ┆ bool │╞═══════╪═════════╪═══════════╡│ 69.99 ┆ 66.49 ┆ true ││ 14.99 ┆ 14.99 ┆ false ││ 19.99 ┆ 19.99 ┆ false │└───────┴─────────┴───────────┘The expressions in one with_columns call run in parallel, so one of them cannot use a column that another one creates in the same call. Chain a second with_columns for that.
filter keeps the rows where a Boolean expression is true. Several predicates separated by commas must all be true. Combine conditions with & (and), | (or) and ~ (not), each comparison in parentheses:
big_online = sales.filter( pl.col("channel") == "online", pl.col("revenue") > 1000,)promo = sales.filter((pl.col("discount") >= 0.1) | (pl.col("quantity") >= 10))print(big_online.height, promo.height)print(sales.filter(pl.col("region").is_in(["North", "West"])).height)print(sales.filter(pl.col("unit_price").is_between(50, 100)).height)398 395896884969is_in tests membership in a list. is_between(50, 100) includes both ends by default. You can also select several columns at once: pl.col("unit_price", "revenue"), every column of a dtype with pl.col(pl.Float64), or every column except some with pl.all().exclude("order_id"). A selector from polars.selectors picks columns by dtype or name: import polars.selectors as cs, then sales.select(cs.numeric()) keeps the four number columns.
Conditional columns: when, then, otherwise
Section titled “Conditional columns: when, then, otherwise”pl.when(condition).then(value).otherwise(other) is Polars’ if/else for a whole column. Chain more .when().then() pairs for more branches. The first true condition wins, as in an if/elif chain:
sized = sales.with_columns( order_size=pl.when(pl.col("quantity") >= 10) .then(pl.lit("bulk")) .when(pl.col("quantity") > 1) .then(pl.lit("multi")) .otherwise(pl.lit("single")))print(sized.group_by("order_size").agg(pl.len().alias("lines")).sort("order_size"))shape: (3, 2)┌────────────┬───────┐│ order_size ┆ lines ││ --- ┆ --- ││ str ┆ u32 │╞════════════╪═══════╡│ bulk ┆ 29 ││ multi ┆ 5630 ││ single ┆ 14569 │└────────────┴───────┘pl.lit("bulk") makes a literal expression: a constant value. Inside then(), a plain string means a column name, so then("bulk") would look for a column called bulk. Wrap constant text in pl.lit(). pl.len() counts the rows of each group. This is the bucket rule of module 25, written as one expression.
Text and dates: the .str and .dt namespaces
Section titled “Text and dates: the .str and .dt namespaces”Methods for one family of dtypes sit behind an attribute of the expression: .str for text, .dt for dates and times, .list for lists. This group of methods is an expression namespace. It is the Polars version of the pandas .str and .dt accessors.
print( products.select( "product", pl.col("product").str.to_uppercase().alias("upper"), pl.col("product").str.len_chars().alias("chars"), pl.col("product").str.contains("Running").alias("running"), ).head(4))shape: (4, 4)┌─────────────────────────────┬─────────────────────────────┬───────┬─────────┐│ product ┆ upper ┆ chars ┆ running ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ str ┆ u32 ┆ bool │╞═════════════════════════════╪═════════════════════════════╪═══════╪═════════╡│ Wireless Earbuds ┆ WIRELESS EARBUDS ┆ 16 ┆ false ││ Noise-Cancelling Headphones ┆ NOISE-CANCELLING HEADPHONES ┆ 27 ┆ false ││ 55-inch 4K Smart TV ┆ 55-INCH 4K SMART TV ┆ 19 ┆ false ││ 14-inch Ultrabook Laptop ┆ 14-INCH ULTRABOOK LAPTOP ┆ 24 ┆ false │└─────────────────────────────┴─────────────────────────────┴───────┴─────────┘Other common .str methods are strip_chars(), replace_all("-", " "), starts_with("P0"), slice(0, 3), split(" ") and to_date("%d/%m/%Y"), which parses text dates in a given format. Text patterns in contains and replace_all are regular expressions (module 09) unless you pass literal=True.
The .dt namespace reads parts of a date and rounds dates down to a period:
print( sales.select( "order_date", pl.col("order_date").dt.year().alias("year"), pl.col("order_date").dt.month().alias("month"), pl.col("order_date").dt.weekday().alias("weekday"), pl.col("order_date").dt.truncate("1mo").alias("month_start"), pl.col("order_date").dt.strftime("%b %Y").alias("label"), ).head(3))shape: (3, 6)┌────────────┬──────┬───────┬─────────┬─────────────┬──────────┐│ order_date ┆ year ┆ month ┆ weekday ┆ month_start ┆ label ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ date ┆ i32 ┆ i8 ┆ i8 ┆ date ┆ str │╞════════════╪══════╪═══════╪═════════╪═════════════╪══════════╡│ 2023-01-01 ┆ 2023 ┆ 1 ┆ 7 ┆ 2023-01-01 ┆ Jan 2023 ││ 2023-01-01 ┆ 2023 ┆ 1 ┆ 7 ┆ 2023-01-01 ┆ Jan 2023 ││ 2023-01-01 ┆ 2023 ┆ 1 ┆ 7 ┆ 2023-01-01 ┆ Jan 2023 │└────────────┴──────┴───────┴─────────┴─────────────┴──────────┘weekday() counts from Monday = 1 to Sunday = 7 (the ISO rule, unlike pandas, which starts at Monday = 0). 2023-01-01 was a Sunday. truncate("1mo") rounds each date down to the first day of its month, which makes a monthly group key. Period strings combine a number and a unit: "1d", "1w", "1mo", "1q", "1y".
group_by and agg, and row order
Section titled “group_by and agg, and row order”group_by(keys).agg(exprs) is split-apply-combine (module 25) in one call. Each expression in agg runs once per group:
by_region = ( sales.group_by("region") .agg( pl.col("revenue").sum().round(2).alias("revenue"), pl.len().alias("lines"), pl.col("order_id").n_unique().alias("orders"), pl.col("revenue").mean().round(2).alias("avg_line"), ) .sort("revenue", descending=True))print(by_region)shape: (4, 5)┌────────┬───────────┬───────┬────────┬──────────┐│ region ┆ revenue ┆ lines ┆ orders ┆ avg_line ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ str ┆ f64 ┆ u32 ┆ u32 ┆ f64 │╞════════╪═══════════╪═══════╪════════╪══════════╡│ East ┆ 993683.72 ┆ 5396 ┆ 4002 ┆ 184.15 ││ South ┆ 891766.07 ┆ 5144 ┆ 3766 ┆ 173.36 ││ North ┆ 888229.47 ┆ 4966 ┆ 3612 ┆ 178.86 ││ West ┆ 822844.57 ┆ 4722 ┆ 3497 ┆ 174.26 │└────────┴───────────┴───────┴────────┴──────────┘first_seen = sales.group_by("region", maintain_order=True).agg(pl.len().alias("lines"))print(first_seen)print(sales["region"].head(4).to_list())shape: (4, 2)┌────────┬───────┐│ region ┆ lines ││ --- ┆ --- ││ str ┆ u32 │╞════════╪═══════╡│ West ┆ 4722 ││ South ┆ 5144 ││ East ┆ 5396 ││ North ┆ 4966 │└────────┴───────┘['West', 'West', 'South', 'West']maintain_order=True lists the regions in the order of their first rows: the first line of the file is in the West. It is a little slower than the default. Sort when you need a business order (largest first); keep the order when the data is already sorted (by date, for example).
Window expressions with over
Section titled “Window expressions with over”A window expression computes a value per group and writes it back to every row of that group. You add .over(keys) to any expression. It is the Polars form of the pandas groupby().transform() and of the SQL OVER (PARTITION BY ...) of module 30.
shares = sales.select( "order_id", "product", "revenue", order_total=pl.col("revenue").sum().over("order_id"), share=(pl.col("revenue") / pl.col("revenue").sum().over("order_id")).round(3),)print(shares.filter(pl.col("order_id") == "O000004"))shape: (2, 5)┌──────────┬─────────────────────────────┬─────────┬─────────────┬───────┐│ order_id ┆ product ┆ revenue ┆ order_total ┆ share ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 ┆ f64 ┆ f64 │╞══════════╪═════════════════════════════╪═════════╪═════════════╪═══════╡│ O000004 ┆ Slim Fit Jeans ┆ 59.99 ┆ 284.09 ┆ 0.211 ││ O000004 ┆ Noise-Cancelling Headphones ┆ 224.1 ┆ 284.09 ┆ 0.789 │└──────────┴─────────────────────────────┴─────────┴─────────────┴───────┘Order O000004 has two lines. sum().over("order_id") gives both lines the order total, so each line can show its share of the order. No join is needed. Windows can also follow an order: pl.col("revenue").cum_sum().over("store_id", order_by="order_date") gives each store’s running total, and pl.col("revenue").rank(descending=True).over("region") ranks each line inside its region.
The lazy API: scan, plan, collect
Section titled “The lazy API: scan, plan, collect”The functions so far are eager: each line runs at once and returns a DataFrame. The lazy API works in three stages:
pl.scan_csv()orpl.scan_parquet()returns a LazyFrame: a description of where the data is. It reads no rows.- Each method you chain (
filter,with_columns,join,group_by) adds a step to a query plan, the tree of steps that produces the result. collect()hands the plan to the query optimizer, which rewrites it into a faster plan with the same result, and then runs it.
flowchart LR
S["scan_csv()<br/>LazyFrame"] --> P["filter / join /<br/>group_by ...<br/>query plan"]
P --> O["optimizer<br/>rewrites the plan"]
O --> C["collect()<br/>DataFrame"]
query = ( pl.scan_csv("data/sales.csv", try_parse_dates=True) .filter(pl.col("channel") == "online") .group_by("category") .agg(pl.col("revenue").sum().round(2)) .sort("revenue", descending=True))print(type(query).__name__)print(query.collect_schema())LazyFrameSchema({'category': String, 'revenue': Float64})Nothing has been read yet, except the CSV header and a few rows that tell Polars the dtypes. collect_schema() shows the columns the result will have. explain() prints the optimized plan. Read it from the bottom up:
print(query.explain())SORT BY [descending: [true]] [col("revenue")] AGGREGATE[maintain_order: false] [col("revenue").sum().round()] BY [col("category")] FROM simple π 2/2 ["category", "revenue"] Csv SCAN [data/sales.csv] PROJECT 3/13 COLUMNS SELECTION: col("channel") == "online" ESTIMATED ROWS: 20653Two rewrites are visible in the scan step at the bottom:
- Projection pushdown:
PROJECT 3/13 COLUMNS. The query uses onlychannel,categoryandrevenue, so the CSV reader parses 3 of the 13 columns. Theπline above it (“pi”, for projection) is that column list. - Predicate pushdown:
SELECTION: col("channel") == "online". The filter moved into the reader. Rows that fail it are dropped while the file is read, before any later step sees them.
A predicate is a condition that is true or false for each row. query.explain(optimized=False) shows the plan as you wrote it, with a separate FILTER step after a scan of all 13 columns. Now run it:
online_by_category = query.collect()print(online_by_category)shape: (6, 2)┌─────────────┬───────────┐│ category ┆ revenue ││ --- ┆ --- ││ str ┆ f64 │╞═════════════╪═══════════╡│ Electronics ┆ 767072.48 ││ Home ┆ 284066 ││ Sports ┆ 226771.66 ││ Clothing ┆ 133153.32 ││ Beauty ┆ 63758.35 ││ Books ┆ 44644.66 │└─────────────┴───────────┘A LazyFrame can be collected many times, and each collect() reads the file again. Call df.lazy() to turn an eager DataFrame into a LazyFrame, so a long chain still gets optimized. For files larger than memory, collect(engine="streaming") runs the plan in batches.
left.join(right, on=key, how=...) combines two tables on matching key values, like pd.merge and SQL JOIN. Polars has seven join types:
how= |
Keeps | Typical question |
|---|---|---|
"inner" (default) |
rows whose key exists in both tables | sales lines with their store details |
"left" |
every left row; nulls where the right has no match | all products, with sales if any |
"right" |
every right row | rarely needed: swap the tables and use "left" |
"full" |
every row of both tables | compare two versions of a list |
"semi" |
left rows that have a match; no right columns | which stores sold something in January? |
"anti" |
left rows that have no match | which products never sold? |
"cross" |
every pair of rows (no key) | all store × month combinations |
A semi join filters the left table to the rows whose key appears in the right table, without adding its columns. An anti join (module 25) keeps the rows whose key does not appear. Both are faster and clearer than a join followed by a filter.
targets = pl.DataFrame( {"store_id": ["S01", "S07", "S13"], "target": [400_000, 450_000, 50_000]})keep = {"on": "store_id", "maintain_order": "left"}with_city = targets.join(stores, how="left", **keep)print(with_city.select("store_id", "target", "city"))print(targets.join(stores, how="semi", **keep)["store_id"].to_list())print(targets.join(stores, how="anti", **keep)["store_id"].to_list())shape: (3, 3)┌──────────┬────────┬──────────┐│ store_id ┆ target ┆ city ││ --- ┆ --- ┆ --- ││ str ┆ i64 ┆ str │╞══════════╪════════╪══════════╡│ S01 ┆ 400000 ┆ Chicago ││ S07 ┆ 450000 ┆ New York ││ S13 ┆ 50000 ┆ null │└──────────┴────────┴──────────┘['S01', 'S07']['S13']maintain_order="left" keeps the row order of targets; the dict keep passes the same two options to all three joins. Store S13 does not exist, so the left join gives it a null city, the semi join drops it and the anti join keeps only it. Three join options prevent silent errors:
| Option | Effect |
|---|---|
validate="m:1" |
raise an error unless each key appears at most once in the right table (many-to-one). Use it for every fact-to-dimension join. |
maintain_order="left" |
keep the row order of the left table. Without it, the row order of a join is not guaranteed. |
coalesce=True |
in a full join, merge the two key columns into one |
Reshape: pivot and unpivot
Section titled “Reshape: pivot and unpivot”Long data has one row per measurement; wide data spreads one variable across columns (module 25). pivot makes long data wide. unpivot makes wide data long; it is the Polars name for the pandas melt.
long = pl.DataFrame( { "region": ["East", "East", "West", "West"], "channel": ["online", "store", "online", "store"], "revenue": [412_000.0, 581_684.0, 360_000.0, 462_845.0], })wide = long.pivot(on="channel", index="region", values="revenue")print(wide)print(wide.unpivot(index="region", variable_name="channel", value_name="revenue"))shape: (2, 3)┌────────┬────────┬────────┐│ region ┆ online ┆ store ││ --- ┆ --- ┆ --- ││ str ┆ f64 ┆ f64 │╞════════╪════════╪════════╡│ East ┆ 412000 ┆ 581684 ││ West ┆ 360000 ┆ 462845 │└────────┴────────┴────────┘shape: (4, 3)┌────────┬─────────┬─────────┐│ region ┆ channel ┆ revenue ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 │╞════════╪═════════╪═════════╡│ East ┆ online ┆ 412000 ││ West ┆ online ┆ 360000 ││ East ┆ store ┆ 581684 ││ West ┆ store ┆ 462845 │└────────┴─────────┴─────────┘on names the column whose values become new column names. index names the column that stays as row keys. values names the cells. When several rows share an index and an on value, pass aggregate_function="sum" (or "mean", "len", …). The new columns appear in the order in which their values first appear, so sort the long table first if the column order matters. A LazyFrame can pivot too, but it needs on_columns=[...]: the optimizer must know the new column names before it reads any data.
Polars and pandas side by side
Section titled “Polars and pandas side by side”The two libraries answer the same questions with different code. Here is one task in both: the three categories with the highest online revenue in 2024. The pandas version needs the pandas display setup of modules 24 and 25:
import pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)top_pl = ( sales.filter( pl.col("channel") == "online", pl.col("order_date").dt.year() == 2024, ) .group_by("category") .agg(pl.col("revenue").sum().round(2)) .sort("revenue", descending=True) .head(3))print(top_pl)shape: (3, 2)┌─────────────┬───────────┐│ category ┆ revenue ││ --- ┆ --- ││ str ┆ f64 │╞═════════════╪═══════════╡│ Electronics ┆ 427426.51 ││ Home ┆ 181857.19 ││ Sports ┆ 143396.72 │└─────────────┴───────────┘sales_pd = pd.read_csv("data/sales.csv", parse_dates=["order_date"])mask = (sales_pd["channel"] == "online") & (sales_pd["order_date"].dt.year == 2024)top_pd = ( sales_pd[mask] .groupby("category", as_index=False)["revenue"] .sum() .round({"revenue": 2}) .sort_values("revenue", ascending=False) .head(3))print(top_pd) category revenue3 Electronics 427426.514 Home 181857.195 Sports 143396.72The numbers are equal. The pandas result keeps index labels from the group order (the numbers on the left); the Polars result has none. Common translations:
| pandas | Polars |
|---|---|
df["col"], df[["a", "b"]] |
df["col"], df.select("a", "b") |
df[df["x"] > 0], df.query("x > 0") |
df.filter(pl.col("x") > 0) |
df.assign(y=df["x"] * 2) |
df.with_columns(y=pl.col("x") * 2) |
df.sort_values("x", ascending=False) |
df.sort("x", descending=True) |
df.groupby("k").agg(total=("x", "sum")) |
df.group_by("k").agg(total=pl.col("x").sum()) |
df.groupby("k")["x"].transform("sum") |
pl.col("x").sum().over("k") |
np.where(cond, a, b) |
pl.when(cond).then(a).otherwise(b) |
df.merge(other, on="k", how="left") |
df.join(other, on="k", how="left") |
df.pivot_table(index=, columns=, values=) |
df.pivot(on=, index=, values=) |
df.melt(id_vars=["k"]) |
df.unpivot(index="k") |
df["s"].str.upper() |
pl.col("s").str.to_uppercase() |
df["x"].isna(), df.fillna(0) |
pl.col("x").is_null(), df.fill_null(0) |
len(df), df.shape |
df.height, df.shape |
Converting between Polars and pandas
Section titled “Converting between Polars and pandas”Many libraries still expect pandas: seaborn, statsmodels, and older scikit-learn code. Convert at the boundary with to_pandas() and pl.from_pandas(). Both use pyarrow, which the course environment installs.
as_pd = top_pl.to_pandas()print(type(as_pd).__name__, as_pd.shape)print(as_pd.dtypes)back = pl.from_pandas(top_pd)print(back.schema)print(back.equals(top_pl))DataFrame (3, 2)category strrevenue float64dtype: objectSchema({'category': String, 'revenue': Float64})Trueto_pandas() gives a fresh pandas DataFrame with a default RangeIndex. from_pandas() drops the pandas index unless you pass include_index=True. equals() compares two Polars DataFrames column by column: the names, their order and every value. It does not compare dtypes, so an Int32 and an Int64 column with the same numbers are equal. Tests use polars.testing.assert_frame_equal(), which also checks the dtypes. For a NumPy array (the input of most scikit-learn models), call df.to_numpy() directly.
Choosing pandas, Polars or SQL with DuckDB
Section titled “Choosing pandas, Polars or SQL with DuckDB”DuckDB (module 30) runs SQL on Polars and pandas DataFrames that sit in Python variables, and it can return a Polars DataFrame with .pl():
import duckdb
by_channel = duckdb.sql( "SELECT channel, round(sum(revenue), 2) AS revenue " "FROM sales GROUP BY channel ORDER BY channel").pl()print(by_channel)shape: (2, 2)┌─────────┬────────────┐│ channel ┆ revenue ││ --- ┆ --- ││ str ┆ f64 │╞═════════╪════════════╡│ online ┆ 1519466.47 ││ store ┆ 2077057.36 │└─────────┴────────────┘DuckDB found the Polars DataFrame sales by its variable name. All three tools read the same Arrow data, so you can mix them in one project:
| Situation | Choose | Why |
|---|---|---|
| Exploring a small table, plotting with seaborn, statsmodels formulas | pandas | the widest ecosystem; most tutorials and libraries expect it |
| A data pipeline over millions of rows, or many files, on one machine | Polars (lazy) | multithreaded, optimized, low memory, strict types catch bad data |
| A team that thinks in SQL, or data already in a database or Parquet folder | SQL with DuckDB | one declarative query; no Python knowledge needed to review it |
| Time-series resampling with a datetime index, many legacy notebooks | pandas | its index tools and the existing code base |
| Feature tables for a model | Polars or DuckDB, then to_numpy() / to_pandas() |
fast preparation; convert once at the boundary |
| Data larger than memory | Polars streaming or DuckDB | both process the data in batches |
There is no single winner. pandas is the common language of Python data science. Polars is the faster and stricter engine for pipelines. SQL is the language that every database and analyst shares.
Worked examples
Section titled “Worked examples”Example 1 — Audit the sales table after loading it
Section titled “Example 1 — Audit the sales table after loading it”Goal: Before a regional report uses data/sales.csv, check that its dtypes, keys and revenue formula match the data dictionary, and make it smaller in memory.
Step 1 — Check the schema against the expected dtypes
Section titled “Step 1 — Check the schema against the expected dtypes”sales = pl.read_csv("data/sales.csv", try_parse_dates=True)expected = { "order_date": pl.Date, "quantity": pl.Int64, "unit_price": pl.Float64, "revenue": pl.Float64,}for name, dtype in expected.items(): print(f"{name:<11} {sales.schema[name]!s:<8} ok={sales.schema[name] == dtype}")order_date Date ok=Truequantity Int64 ok=Trueunit_price Float64 ok=Truerevenue Float64 ok=TrueA wrong dtype is the first sign of a broken file: a String revenue column means a stray text value, and a String date means a format that try_parse_dates did not recognize. Checking it in code turns a visual check into a test.
Step 2 — Count nulls and duplicate keys
Section titled “Step 2 — Count nulls and duplicate keys”nulls = sales.null_count().sum_horizontal().item()dup_keys = sales.select("order_id", "product_id").is_duplicated().sum()print("null cells:", nulls)print("duplicate (order_id, product_id):", dup_keys)print("orders:", sales["order_id"].n_unique(), "lines:", sales.height)null cells: 0duplicate (order_id, product_id): 0orders: 14877 lines: 20228null_count() returns one row with the null count of each column. sum_horizontal() adds across the columns of that row. The pair (order_id, product_id) is the key of a line, so it must be unique. One order has 1 to 3 lines, which is why there are fewer orders than lines.
Step 3 — Recompute revenue and compare
Section titled “Step 3 — Recompute revenue and compare”formula = pl.col("unit_price") * pl.col("quantity") * (1 - pl.col("discount"))check = sales.with_columns(expected=formula.round(2)).filter( (pl.col("expected") - pl.col("revenue")).abs() > 0.01)print("lines that break the revenue formula:", check.height)lines that break the revenue formula: 0The formula holds on every line, within the 0.01 tolerance that the data dictionary recommends. Writing the check as a filter gives you the bad rows themselves when the count is not 0.
Step 4 — Store low-cardinality text as Enum
Section titled “Step 4 — Store low-cardinality text as Enum”regions = ["North", "South", "East", "West"]compact = sales.with_columns( pl.col("region").cast(pl.Enum(regions)), pl.col("channel").cast(pl.Enum(["store", "online"])), pl.col("category").cast(pl.Categorical),)before = round(sales.estimated_size("mb"), 2)after = round(compact.estimated_size("mb"), 2)print(before, "MB ->", after, "MB")print(compact.schema["region"])1.78 MB -> 1.58 MBEnum(categories=['North', 'South', 'East', 'West'])An Enum dtype stores text from a fixed, known list of values as small integer codes. A Categorical dtype does the same, but it learns the list from the data. Both save memory and speed up grouping. An Enum also rejects any value outside its list, which makes it a free data check, and it sorts in the list’s order (North, South, East, West), not alphabetically.
Common mistakes:
- Forgetting
try_parse_dates=True.order_datestaysString, and.dt.month()raises an error. - Comparing recomputed money with
==. Floats differ in the last digits; compare with a tolerance, as in Step 3. - Casting to
pl.Enumwith an incomplete list. A value that is not in the list raises an error. That is useful as a check, but list every valid value.
Example 2 — Build a monthly gross-profit report
Section titled “Example 2 — Build a monthly gross-profit report”Goal: Finance wants revenue, gross profit, margin and the month-over-month change for each month of 2024. The unit cost is in data/products.csv, so the report needs a join.
Step 1 — Add the unit cost with a validated left join
Section titled “Step 1 — Add the unit cost with a validated left join”lines = sales.join( products.select("product_id", "unit_cost"), on="product_id", how="left", validate="m:1", maintain_order="left",)print(lines.height == sales.height, lines["unit_cost"].null_count())print(lines.select("order_id", "product_id", "revenue", "unit_cost").head(3))True 0shape: (3, 4)┌──────────┬────────────┬─────────┬───────────┐│ order_id ┆ product_id ┆ revenue ┆ unit_cost ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 ┆ f64 │╞══════════╪════════════╪═════════╪═══════════╡│ O000001 ┆ P010 ┆ 66.49 ┆ 24 ││ O000002 ┆ P014 ┆ 14.99 ┆ 4.2 ││ O000003 ┆ P015 ┆ 19.99 ┆ 6.1 │└──────────┴────────────┴─────────┴───────────┘validate="m:1" proves that each product_id appears once in products, so the join cannot duplicate sales lines. The row count is unchanged and no line lacks a cost. maintain_order="left" keeps the date order of sales.
Step 2 — Compute gross profit and the month key
Section titled “Step 2 — Compute gross profit and the month key”lines = lines.with_columns( gross_profit=pl.col("revenue") - pl.col("unit_cost") * pl.col("quantity"), month=pl.col("order_date").dt.truncate("1mo"),)show = lines.select("order_date", "month", "revenue", pl.col("gross_profit").round(2))print(show.head(3))shape: (3, 4)┌────────────┬────────────┬─────────┬──────────────┐│ order_date ┆ month ┆ revenue ┆ gross_profit ││ --- ┆ --- ┆ --- ┆ --- ││ date ┆ date ┆ f64 ┆ f64 │╞════════════╪════════════╪═════════╪══════════════╡│ 2023-01-01 ┆ 2023-01-01 ┆ 66.49 ┆ 42.49 ││ 2023-01-01 ┆ 2023-01-01 ┆ 14.99 ┆ 10.79 ││ 2023-01-01 ┆ 2023-01-01 ┆ 19.99 ┆ 13.89 │└────────────┴────────────┴─────────┴──────────────┘Gross profit is revenue minus the cost of the goods sold (module 28). The column keeps every digit; only the printed copy is rounded. truncate("1mo") maps every date to the first day of its month, so all January lines share one key.
Step 3 — Aggregate per month and compute the margin
Section titled “Step 3 — Aggregate per month and compute the margin”monthly = ( lines.filter(pl.col("order_date").dt.year() == 2024) .group_by("month") .agg( pl.col("revenue").sum().round(2).alias("revenue"), pl.col("gross_profit").sum().round(2).alias("gross_profit"), pl.col("order_id").n_unique().alias("orders"), ) .sort("month") .with_columns(margin=(pl.col("gross_profit") / pl.col("revenue")).round(3)))print(monthly)shape: (12, 5)┌────────────┬───────────┬──────────────┬────────┬────────┐│ month ┆ revenue ┆ gross_profit ┆ orders ┆ margin ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ date ┆ f64 ┆ f64 ┆ u32 ┆ f64 │╞════════════╪═══════════╪══════════════╪════════╪════════╡│ 2024-01-01 ┆ 119596.89 ┆ 57327.89 ┆ 474 ┆ 0.479 ││ 2024-02-01 ┆ 106320.41 ┆ 53664.11 ┆ 429 ┆ 0.505 ││ 2024-03-01 ┆ 145567.22 ┆ 71162.12 ┆ 564 ┆ 0.489 ││ 2024-04-01 ┆ 114917.5 ┆ 59136 ┆ 543 ┆ 0.515 ││ 2024-05-01 ┆ 128716.36 ┆ 66017.96 ┆ 606 ┆ 0.513 ││ … ┆ … ┆ … ┆ … ┆ … ││ 2024-08-01 ┆ 151791.33 ┆ 77385.13 ┆ 658 ┆ 0.51 ││ 2024-09-01 ┆ 141654.74 ┆ 72044.84 ┆ 616 ┆ 0.509 ││ 2024-10-01 ┆ 166147.92 ┆ 84013.62 ┆ 675 ┆ 0.506 ││ 2024-11-01 ┆ 268466.55 ┆ 128116.65 ┆ 1018 ┆ 0.477 ││ 2024-12-01 ┆ 302911.77 ┆ 141714.37 ┆ 1237 ┆ 0.468 │└────────────┴───────────┴──────────────┴────────┴────────┘The sort("month") makes the order deterministic and puts the months in calendar order. The margin is computed after the aggregation, from the monthly totals. The mean of the line margins would give each small line as much weight as a television.
Step 4 — Add the month-over-month change
Section titled “Step 4 — Add the month-over-month change”report = monthly.with_columns( mom_pct=(pl.col("revenue").pct_change() * 100).round(1), month=pl.col("month").dt.strftime("%Y-%m"),).select("month", "revenue", "margin", "mom_pct")print(report.tail(4))shape: (4, 4)┌─────────┬───────────┬────────┬─────────┐│ month ┆ revenue ┆ margin ┆ mom_pct ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ f64 ┆ f64 ┆ f64 │╞═════════╪═══════════╪════════╪═════════╡│ 2024-09 ┆ 141654.74 ┆ 0.509 ┆ -6.7 ││ 2024-10 ┆ 166147.92 ┆ 0.506 ┆ 17.3 ││ 2024-11 ┆ 268466.55 ┆ 0.477 ┆ 61.6 ││ 2024-12 ┆ 302911.77 ┆ 0.468 ┆ 12.8 │└─────────┴───────────┴────────┴─────────┘pct_change() divides each value by the one above it and subtracts 1. It depends on row order, which is why Step 3 sorted by month. The table shows the jump into November (+61.6%) and the December peak, the holiday seasonality that the data dictionary describes.
Common mistakes:
- Joining without
validate. A duplicate row in a dimension table silently doubles some sales lines and inflates every total. - Calling
pct_change()orshift()on an unsortedgroup_byresult. The output changes from run to run. - Averaging line margins instead of dividing the summed profit by the summed revenue.
Example 3 — Run a lazy query over two files
Section titled “Example 3 — Run a lazy query over two files”Goal: Rank the cities by 2024 online revenue. Write the query lazily, inspect what Polars will read, and check the result against the eager version.
Step 1 — Describe the query
Section titled “Step 1 — Describe the query”city_query = ( pl.scan_csv("data/sales.csv", try_parse_dates=True) .filter( pl.col("channel") == "online", pl.col("order_date").dt.year() == 2024, ) .join(pl.scan_csv("data/stores.csv"), on="store_id", how="left", validate="m:1") .group_by("city") .agg(pl.col("revenue").sum().round(2).alias("online_revenue")) .sort("online_revenue", descending=True))print(city_query.collect_schema())Schema({'city': String, 'online_revenue': Float64})Two scan_csv calls point at two files. Nothing is read yet. The schema already shows the result’s two columns.
Step 2 — Read the optimized plan
Section titled “Step 2 — Read the optimized plan”print(city_query.explain())SORT BY [descending: [true]] [col("online_revenue")] AGGREGATE[maintain_order: false] [col("revenue").sum().round().alias("online_revenue")] BY [col("city")] FROM simple π 2/2 ["city", "revenue"] LEFT JOIN: LEFT PLAN ON: [col("store_id")] simple π 2/2 ["revenue", "store_id"] Csv SCAN [data/sales.csv] PROJECT 4/13 COLUMNS SELECTION: (col("channel") == "online") & (col("order_date").dt.year() == 2024) ESTIMATED ROWS: 20653 RIGHT PLAN ON: [col("store_id")] simple π 2/2 ["city", "store_id"] Csv SCAN [data/stores.csv] PROJECT 2/5 COLUMNS ESTIMATED ROWS: 13 END LEFT JOINRead from the bottom. The sales scan parses 4 of the 13 columns (channel, order_date, revenue, store_id), and both filters run inside it. The stores scan parses 2 of its 5 columns. The filters moved below the join, so the join sees only the online lines of 2024 (Step 4 counts them) instead of all 20,228 lines. ESTIMATED ROWS is a guess that Polars makes from the file size before it reads; the real count is known only after collect().
The optimizer also changes join types when it is safe. Had the query filtered on a store column after the left join (for example pl.col("city") == "Denver"), sales lines without a store could never pass that filter, and the plan would show an INNER JOIN with the filter pushed into the stores scan:
denver = ( pl.scan_csv("data/sales.csv") .join(pl.scan_csv("data/stores.csv"), on="store_id", how="left", validate="m:1") .filter(pl.col("city") == "Denver") .select("order_id", "revenue"))for line in denver.explain().splitlines(): if "JOIN" in line or "SELECTION" in line: print(line.strip())INNER JOIN:SELECTION: col("city") == "Denver"END INNER JOINThe plan has no LEFT JOIN any more, and the city filter sits in the stores scan, so only the Denver row of stores reaches the join.
Step 3 — Collect the result
Section titled “Step 3 — Collect the result”by_city = city_query.collect()print(by_city)shape: (12, 2)┌───────────────┬────────────────┐│ city ┆ online_revenue ││ --- ┆ --- ││ str ┆ f64 │╞═══════════════╪════════════════╡│ New York ┆ 114295.65 ││ Houston ┆ 103832.42 ││ Chicago ┆ 95933.82 ││ Seattle ┆ 93519.8 ││ Atlanta ┆ 75783.17 ││ … ┆ … ││ Philadelphia ┆ 64266.23 ││ San Francisco ┆ 60744.08 ││ Miami ┆ 52053.44 ││ Detroit ┆ 49953.04 ││ Denver ┆ 41009.88 │└───────────────┴────────────────┘collect() runs the plan and returns an eager DataFrame. New York fulfills the most online revenue and Denver, open only since June 2023, the least.
Step 4 — Compare with the eager version
Section titled “Step 4 — Compare with the eager version”online_2024 = sales.filter( pl.col("channel") == "online", pl.col("order_date").dt.year() == 2024,)eager = ( online_2024.join(stores, on="store_id", how="left", validate="m:1") .group_by("city") .agg(pl.col("revenue").sum().round(2).alias("online_revenue")) .sort("online_revenue", descending=True))print(eager.equals(by_city))share = online_2024.height / sales.heightprint(online_2024.height, "of", sales.height, f"lines pass the filters ({share:.1%})")True5150 of 20228 lines pass the filters (25.5%)The same chain gives the same table. The filters keep about a quarter of the lines, the rows that the lazy join sees in Step 2. Lazy and eager code look almost identical; the lazy one only starts with scan_* and ends with collect(). On 20,000 rows the speed difference is tiny. On a 5 GB file, reading 4 columns instead of 13 and dropping three quarters of the rows during the read decides whether the query fits in memory.
Common mistakes:
- Calling
print(city_query)and expecting data. A LazyFrame prints its plan. Callcollect(). - Calling
collect()after every step. Each call runs the plan and ends the optimization. Collect once, at the end. - Using
pl.read_csv()inside a lazy chain. Usepl.scan_csv(), so the optimizer can push the filters and the column list into the reader.
Example 4 — Find the top products in each region with window expressions
Section titled “Example 4 — Find the top products in each region with window expressions”Goal: For a regional buying meeting, list the two products with the highest revenue in each region, with their share of the region’s revenue.
Step 1 — Aggregate revenue per region and product
Section titled “Step 1 — Aggregate revenue per region and product”region_product = ( sales.group_by("region", "product") .agg(pl.col("revenue").sum().round(2).alias("revenue")) .sort("region", "revenue", descending=[False, True]))print(region_product.height)print(region_product.head(3))120shape: (3, 3)┌────────┬─────────────────────────────┬──────────┐│ region ┆ product ┆ revenue ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 │╞════════╪═════════════════════════════╪══════════╡│ East ┆ 55-inch 4K Smart TV ┆ 195239.7 ││ East ┆ 14-inch Ultrabook Laptop ┆ 192687.3 ││ East ┆ Noise-Cancelling Headphones ┆ 60619.05 │└────────┴─────────────────────────────┴──────────┘4 regions × 30 products give 120 rows. The two-column sort puts regions in alphabetical order and products by falling revenue inside each region.
Step 2 — Rank and share inside each region
Section titled “Step 2 — Rank and share inside each region”region_total = pl.col("revenue").sum().over("region")ranked = region_product.with_columns( rank=pl.col("revenue").rank("ordinal", descending=True).over("region"), share_pct=(100 * pl.col("revenue") / region_total).round(1),)print(ranked.head(4))shape: (4, 5)┌────────┬─────────────────────────────┬──────────┬──────┬───────────┐│ region ┆ product ┆ revenue ┆ rank ┆ share_pct ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 ┆ u32 ┆ f64 │╞════════╪═════════════════════════════╪══════════╪══════╪═══════════╡│ East ┆ 55-inch 4K Smart TV ┆ 195239.7 ┆ 1 ┆ 19.6 ││ East ┆ 14-inch Ultrabook Laptop ┆ 192687.3 ┆ 2 ┆ 19.4 ││ East ┆ Noise-Cancelling Headphones ┆ 60619.05 ┆ 3 ┆ 6.1 ││ East ┆ Espresso Machine ┆ 50343.25 ┆ 4 ┆ 5.1 │└────────┴─────────────────────────────┴──────────┴──────┴───────────┘rank("ordinal", descending=True) numbers the products 1, 2, 3, … from the highest revenue. .over("region") restarts the ranking in each region. The share divides each product’s revenue by region_total, an expression stored in a variable and also computed with over. Expressions are ordinary Python objects, so you can name them and reuse them. Both windows run in one with_columns, in parallel.
Step 3 — Keep the top two per region
Section titled “Step 3 — Keep the top two per region”top2 = ranked.filter(pl.col("rank") <= 2)top2 = top2.select("region", "rank", "product", "share_pct")print(top2)shape: (8, 4)┌────────┬──────┬──────────────────────────┬───────────┐│ region ┆ rank ┆ product ┆ share_pct ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ u32 ┆ str ┆ f64 │╞════════╪══════╪══════════════════════════╪═══════════╡│ East ┆ 1 ┆ 55-inch 4K Smart TV ┆ 19.6 ││ East ┆ 2 ┆ 14-inch Ultrabook Laptop ┆ 19.4 ││ North ┆ 1 ┆ 55-inch 4K Smart TV ┆ 18.3 ││ North ┆ 2 ┆ 14-inch Ultrabook Laptop ┆ 16.4 ││ South ┆ 1 ┆ 14-inch Ultrabook Laptop ┆ 18.5 ││ South ┆ 2 ┆ 55-inch 4K Smart TV ┆ 15.3 ││ West ┆ 1 ┆ 14-inch Ultrabook Laptop ┆ 19.7 ││ West ┆ 2 ┆ 55-inch 4K Smart TV ┆ 16.3 │└────────┴──────┴──────────────────────────┴───────────┘The 55-inch TV and the ultrabook laptop are the top two in every region. The share_pct column shows that each one brings in 15% to 20% of its region’s revenue. This filter-on-a-window pattern is the “top N per group” query; SQL needs a subquery or QUALIFY for it (module 30).
Common mistakes:
- Using
group_byfor the share.group_byreturns one row per region, so you must join the totals back.overdoes it in one expression. - Ranking with the default method on tied values.
rank()gives ties the average rank (for example 1.5). Choose"ordinal","min"or"dense"on purpose. - Forgetting
descending=Trueinrank. Rank 1 is then the smallest revenue.
Example 5 — Find gaps with semi and anti joins
Section titled “Example 5 — Find gaps with semi and anti joins”Goal: A data engineer checks the first quarter of 2023 for gaps: which products sold nothing, which stores had no sales, and whether the store table has duplicate ids.
Step 1 — Find the products with no sales in Q1 2023
Section titled “Step 1 — Find the products with no sales in Q1 2023”q1 = sales.filter(pl.col("order_date") < pl.date(2023, 4, 1))unsold = products.join(q1, on="product_id", how="anti").select( "product_id", "product", "launch_date")print(unsold.sort("product_id"))shape: (4, 3)┌────────────┬─────────────────────┬─────────────┐│ product_id ┆ product ┆ launch_date ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ date │╞════════════╪═════════════════════╪═════════════╡│ P005 ┆ Smartwatch Series 5 ┆ 2023-09-12 ││ P007 ┆ Robot Vacuum ┆ 2024-02-20 ││ P019 ┆ Fitness Tracker ┆ 2023-05-02 ││ P025 ┆ The Mindful Runner ┆ 2024-04-09 │└────────────┴─────────────────────┴─────────────┘pl.date(2023, 4, 1) builds a date literal. The anti join keeps the products that do not appear in q1. All four launched after March 2023, so the gap is expected, not a data error.
Step 2 — List the stores that did and did not sell
Section titled “Step 2 — List the stores that did and did not sell”active = stores.join(q1, on="store_id", how="semi")inactive = stores.join(q1, on="store_id", how="anti")print(active.height, "active stores")print(inactive.select("store_id", "city", "opened"))11 active storesshape: (1, 3)┌──────────┬────────┬────────────┐│ store_id ┆ city ┆ opened ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ date │╞══════════╪════════╪════════════╡│ S12 ┆ Denver ┆ 2023-06-15 │└──────────┴────────┴────────────┘The semi join returns each matching store once, even though it matches thousands of sales lines. A normal inner join would repeat each store once per line. Denver (S12) opened in June 2023, so it has no sales in Q1.
Step 3 — Catch a duplicate key before it inflates totals
Section titled “Step 3 — Catch a duplicate key before it inflates totals”stores_dirty = pl.concat([stores, stores.filter(pl.col("store_id") == "S01")])print(stores_dirty.height, "store rows")sales.join(stores_dirty, on="store_id", how="left", validate="m:1")13 store rowspolars.exceptions.ComputeError: join keys did not fulfill m:1 validationSomeone appended S01 twice. Without validate, the join would duplicate all 2,220 Chicago lines and add their revenue twice. With validate="m:1", the join stops with a ComputeError and names the broken rule.
Common mistakes:
- Using an inner join plus
unique()to answer “which stores sold?”. A semi join is shorter and does not repeat rows. - Reading an anti-join result as an error list without checking the context. Here, launch and opening dates explain every gap.
- Fixing a duplicate key by dropping duplicates in the sales table. Fix the dimension table, where the duplicate is.
Example 6 — Make a region by quarter table with pivot and unpivot
Section titled “Example 6 — Make a region by quarter table with pivot and unpivot”Goal: A slide needs 2024 revenue by region (rows) and quarter (columns). The analyst also needs the long form back to compute the quarter-over-quarter growth.
Step 1 — Aggregate to long form
Section titled “Step 1 — Aggregate to long form”quarterly = ( sales.filter(pl.col("order_date").dt.year() == 2024) .with_columns(quarter=pl.format("Q{}", pl.col("order_date").dt.quarter())) .group_by("region", "quarter") .agg(pl.col("revenue").sum().round(0).alias("revenue")) .sort("region", "quarter"))print(quarterly.head(5))shape: (5, 3)┌────────┬─────────┬─────────┐│ region ┆ quarter ┆ revenue ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 │╞════════╪═════════╪═════════╡│ East ┆ Q1 ┆ 99878 ││ East ┆ Q2 ┆ 111300 ││ East ┆ Q3 ┆ 124620 ││ East ┆ Q4 ┆ 208967 ││ North ┆ Q1 ┆ 79312 │└────────┴─────────┴─────────┘pl.format("Q{}", ...) builds text from a template: each {} takes the value of the next expression. The sort fixes the row order, and with it the column order of the pivot in the next step.
Step 2 — Pivot to one column per quarter
Section titled “Step 2 — Pivot to one column per quarter”table = quarterly.pivot(on="quarter", index="region", values="revenue")print(table)shape: (4, 5)┌────────┬────────┬────────┬────────┬────────┐│ region ┆ Q1 ┆ Q2 ┆ Q3 ┆ Q4 ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 │╞════════╪════════╪════════╪════════╪════════╡│ East ┆ 99878 ┆ 111300 ┆ 124620 ┆ 208967 ││ North ┆ 79312 ┆ 108102 ┆ 110280 ┆ 180036 ││ South ┆ 89335 ┆ 95449 ┆ 113298 ┆ 184183 ││ West ┆ 102960 ┆ 84637 ┆ 94237 ┆ 164340 │└────────┴────────┴────────┴────────┴────────┘Each quarter label became a column, in the order Q1 to Q4 because the long table was sorted. Every region has its largest quarter in Q4, the holiday season.
Step 3 — Unpivot and compute the quarter-over-quarter growth
Section titled “Step 3 — Unpivot and compute the quarter-over-quarter growth”growth = ( table.unpivot(index="region", variable_name="quarter", value_name="revenue") .sort("region", "quarter") .with_columns( qoq_pct=(pl.col("revenue").pct_change().over("region") * 100).round(1) ))print(growth.filter(pl.col("quarter") == "Q4"))shape: (4, 4)┌────────┬─────────┬─────────┬─────────┐│ region ┆ quarter ┆ revenue ┆ qoq_pct ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 ┆ f64 │╞════════╪═════════╪═════════╪═════════╡│ East ┆ Q4 ┆ 208967 ┆ 67.7 ││ North ┆ Q4 ┆ 180036 ┆ 63.3 ││ South ┆ Q4 ┆ 184183 ┆ 62.6 ││ West ┆ Q4 ┆ 164340 ┆ 74.4 │└────────┴─────────┴─────────┴─────────┘unpivot turns the four quarter columns back into rows. pct_change().over("region") compares each quarter with the previous one inside the same region, so Q1 of West is never compared with Q4 of South. The window relies on the sort by region and quarter.
Common mistakes:
- Pivoting an unsorted
group_byresult. The quarter columns can come out as Q2, Q1, Q4, Q3, and the order changes between runs. - Forgetting
aggregate_functionwhen several rows share an index and anonvalue. Polars raises an error; pass"sum"or aggregate first, as here. - Calling
pct_change()withoutover. The first quarter of each region is then compared with the last quarter of the region before it.
Example 7 — Port a pandas weekday report to Polars
Section titled “Example 7 — Port a pandas weekday report to Polars”Goal: A pandas script computes the average daily revenue per weekday. Port it to Polars, prove that both give the same numbers, and hand the result back to pandas-based code.
Step 1 — Write the report in both libraries
Section titled “Step 1 — Write the report in both libraries”weekday_pl = ( sales.group_by("order_date") .agg(pl.col("revenue").sum()) .with_columns(weekday=pl.col("order_date").dt.weekday()) .group_by("weekday") .agg(pl.col("revenue").mean().round(2).alias("avg_daily_revenue")) .sort("weekday"))print(weekday_pl)shape: (7, 2)┌─────────┬───────────────────┐│ weekday ┆ avg_daily_revenue ││ --- ┆ --- ││ i8 ┆ f64 │╞═════════╪═══════════════════╡│ 1 ┆ 4232.8 ││ 2 ┆ 3942.6 ││ 3 ┆ 4259.46 ││ 4 ┆ 4416.28 ││ 5 ┆ 5597.53 ││ 6 ┆ 6364.66 ││ 7 ┆ 5635.84 │└─────────┴───────────────────┘daily_pd = sales_pd.groupby("order_date", as_index=False)["revenue"].sum()daily_pd["weekday"] = daily_pd["order_date"].dt.day_of_week + 1weekday_pd = ( daily_pd.groupby("weekday", as_index=False)["revenue"] .mean() .round({"revenue": 2}) .rename(columns={"revenue": "avg_daily_revenue"}))print(weekday_pd) weekday avg_daily_revenue0 1 4232.801 2 3942.602 3 4259.463 4 4416.284 5 5597.535 6 6364.666 7 5635.84Both versions sum revenue per day, then average the days per weekday. pandas counts weekdays from 0 and Polars from 1, so the pandas code adds 1. Saturday (6) has the highest average, as the data dictionary says.
Step 2 — Prove that the results match
Section titled “Step 2 — Prove that the results match”from polars.testing import assert_frame_equal
converted = pl.from_pandas(weekday_pd)print(converted.schema)print(converted.equals(weekday_pl))assert_frame_equal(converted, weekday_pl, check_dtypes=False)print("assert_frame_equal passed")Schema({'weekday': Int32, 'avg_daily_revenue': Float64})Trueassert_frame_equal passedThe pandas weekday is int32 and the Polars weekday is Int8. equals() ignores dtypes and finds every value equal. assert_frame_equal() checks dtypes by default, so it would fail here; check_dtypes=False tells it that the different integer widths are expected. It raises an AssertionError with the first difference when the tables differ, which makes it the right tool inside a pytest test (module 14). A test like this is the safest way to port code: keep the old version until the new one gives the same table.
Step 3 — Hand the result to pandas code
Section titled “Step 3 — Hand the result to pandas code”for_plot = weekday_pl.to_pandas().set_index("weekday")print(for_plot.loc[6, "avg_daily_revenue"])print(weekday_pl.to_numpy().shape)6364.66(7, 2)A plotting function written for pandas can take for_plot directly. to_numpy() gives the 2D array that scikit-learn expects. Convert once, at the boundary between your Polars pipeline and the pandas-only tool.
Common mistakes:
- Assuming both libraries number weekdays the same way. pandas starts at Monday = 0, Polars at Monday = 1.
- Comparing tables with
==on whole DataFrames. In Polars,df1 == df2compares cell by cell; usedf1.equals(df2)for oneTrueorFalse. - Converting back and forth inside a loop. Each conversion copies data; convert once.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
Printing a group_by().agg() result without sorting |
Row order changes between runs | .sort(...) or group_by(..., maintain_order=True) |
| Joining without an order option | Row order of the result is not guaranteed | maintain_order="left", or sort after the join |
then("bulk") for a constant text |
ColumnNotFoundError: unable to find column "bulk" |
then(pl.lit("bulk")) |
Using a new column in the same with_columns call |
ColumnNotFoundError |
Chain a second with_columns |
pl.read_csv(path) without try_parse_dates=True |
Dates are String; .dt raises InvalidOperationError |
Pass try_parse_dates=True or parse with .str.to_date() |
pl.col("a") > 0 & pl.col("b") > 0 |
TypeError: the truth value of an Expr is ambiguous |
Parentheses: (pl.col("a") > 0) & (pl.col("b") > 0), or comma-separated predicates in filter |
print(lazy_frame) |
A query plan instead of data | lazy_frame.collect() |
collect() after each step |
Slow; the optimizer sees only small pieces | Build the whole chain, collect once |
Old names from tutorials: groupby, melt, with_row_count, pl.count() |
AttributeError (groupby), AttributeRemovedError (melt, with_row_count) or TypeError (pl.count()) |
group_by, unpivot, with_row_index, pl.len() |
.cut() or .qcut() from older code |
DeprecationWarning |
bin_intervals(breaks, labels=[...], right_closed=True) keeps the cut edges; bin_quantiles or bin_ranks replace qcut. All three are experimental. |
pl.col("x").is_in(other_series) |
DeprecationWarning: is_in with a collection of the same datatype is ambiguous |
is_in(other_series.implode()), or a semi join |
sort("x").head(3) when x has ties |
The third row changes between runs | Add a tie-breaker: sort("x", "order_id") |
map_elements(lambda x: ...) for arithmetic |
PolarsInefficientMapWarning; slow Python loop |
Write the formula as an expression: pl.col("x") * 2 |
df.to_pandas() without pyarrow installed |
ModuleNotFoundError: pyarrow |
pip install pyarrow (the course environment has it) |
Comparing DataFrames with == |
A table of Booleans, not one answer | df1.equals(df2) |
rank() with ties for “top N” |
Ranks like 1.5; rank <= 1 drops both tied rows |
rank("ordinal") or rank("min") |
pct_change() or shift() without a sort or over |
Changes compared across groups or in random order | Sort first; add .over("group") |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Data engineering: nightly jobs scan folders of Parquet files with
pl.scan_parquet("lake/*.parquet"), filter and aggregate them, and write summary tables. The optimizer keeps memory low. - Web back ends: an API endpoint loads a Parquet extract once and answers each request with a fast
filterandgroup_by, for example a dashboard of orders per store. - Log analysis and automation: a script reads millions of access-log lines with
scan_csv, extracts fields with.str, and counts errors per hour with.dt.truncate("1h"). - Tooling: command-line tools convert CSV to Parquet (
pl.read_csv(...).write_parquet(...)) and validate schemas in CI before a file reaches a database.
Summary
Section titled “Summary”- Polars is a fast, multithreaded DataFrame library with no index,
nullfor every missing value and strict dtypes. - Fix the display at the top of a page with
pl.Configso tables stay stable and at most 100 characters wide. - An expression such as
pl.col("revenue") * 0.9is a recipe. A context (select,with_columns,filter,group_by().agg()) runs it on data. when/then/otherwisebuilds conditional columns;.strand.dthold the text and date methods;.over()turns any aggregation into a window column.- The lazy API (
scan_*→ plan →collect()) lets the optimizer push filters and column lists into the reader.explain()shows the plan. - Group, unique and join results have no guaranteed order. Sort, or pass
maintain_order. - Joins take
how="inner","left","full","semi","anti"or"cross". Usevalidate="m:1"for fact-to-dimension joins. pivotmakes long data wide andunpivotmakes it long again.- Convert with
to_pandas()andpl.from_pandas()at the boundary. Choose pandas for its ecosystem, Polars for fast pipelines and DuckDB for SQL.
Self-check questions
Section titled “Self-check questions”Q1. What does pl.col("revenue") * 0.9 compute when Python runs that line?
Answer
Nothing. It builds an expression: a recipe for a column. The multiplication happens only when a context such as select or with_columns runs the expression on a DataFrame.
Q2. You need all columns of sales plus a new gross column. Do you use select or with_columns?
Answer
with_columns. It keeps every existing column and adds (or replaces) the new ones. select returns only the columns that its expressions produce.
Q3. A script prints sales.group_by("region").agg(pl.len()). A colleague runs it and sees the regions in a different order. Why, and how do you fix it?
Answer
Polars computes groups on several threads, so the group order is not deterministic. Add .sort("region") (or another sort), or pass maintain_order=True to group_by.
Q4. Why does pl.when(pl.col("quantity") >= 10).then("bulk").otherwise("single") fail?
Answer
Inside then and otherwise, a plain string is a column name. Polars looks for columns called bulk and single and raises ColumnNotFoundError. Wrap constants in pl.lit("bulk").
Q5. What do predicate pushdown and projection pushdown do in a lazy query over a CSV file?
Answer
Predicate pushdown moves a filter into the file reader, so rows that fail it are dropped while the file is read. Projection pushdown makes the reader parse only the columns that the query uses. Both save time and memory. explain() shows them as SELECTION: and PROJECT k/n COLUMNS in the scan step.
Q6. What is the difference between a semi join and an inner join of stores with sales on store_id?
Answer
The semi join returns each store that has at least one sales line, once, with only the store columns. The inner join returns one row per matching sales line, with the columns of both tables, so each store appears thousands of times.
Q7. How do you add each line’s share of its order’s revenue without a join?
Answer
Use a window expression: pl.col("revenue") / pl.col("revenue").sum().over("order_id"). over computes the sum per order and writes it back to every line of that order.
Q8. What does validate="m:1" protect you from in sales.join(stores, on="store_id", how="left", validate="m:1")?
Answer
From duplicate keys in stores. If a store id appears twice, the join would duplicate all its sales lines and inflate every total. With validate="m:1", Polars raises a ComputeError instead.
Q9. Why does a lazy pivot need on_columns, but an eager pivot does not?
Answer
The optimizer must know the schema of every step before it reads data. The new column names of a pivot come from the data, so the lazy version must be told the list in advance. The eager version has the data already and reads the names from it.
Q10. A project plots with seaborn, fits statsmodels formulas and has a 4 GB folder of Parquet files to aggregate every night. Which tool do you use for which part?
Answer
Use Polars (lazy, scan_parquet) or DuckDB for the nightly aggregation of the large files: they are multithreaded and read only what the query needs. Convert the small aggregated result with to_pandas() for seaborn and statsmodels, which expect pandas.
Q11. What is the Polars 2 name for each of these pandas or old Polars calls: melt, groupby, fillna, pl.count()?
Answer
unpivot, group_by, fill_null and pl.len().
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 26 exercises with hints and full solutions, from expressions to lazy pipelines.
- Mini-project: build a lazy store-performance pipeline and check it against pandas.
- Cheat sheet: every Polars context, expression, join and reshape of this module on one page.
- Part 4 checkpoint: mixed exercises across NumPy, pandas, cleaning, EDA, visualization, statistics, SQL and Polars.
- Next module: 32. Math for ML starts Part 5 with vectors, matrices, gradients and gradient descent in NumPy.