Sub topic 3
Joining DataFrames and Building Lazy Queries
Assume basic Python, method chaining, and tabular data. The examples use Polars expressions rather than row-by-row Python functions.
Joining DataFrames
A join combines rows from two DataFrames using matching key columns. A left join keeps every row from the left DataFrame and adds matching values from the right.
import tempfile
from pathlib import Path
import polars as pl
employees = pl.DataFrame({
"name": ["Ana", "Ben", "Cy"],
"dept": ["eng", "eng", "ops"],
"salary": [120, 100, 80],
})
departments = pl.DataFrame({
"dept": ["eng", "ops"],
"floor": [3, 1],
})
joined = employees.join(departments, on="dept", how="left")
print(joined)
wide = joined.pivot(
on="dept",
index="name",
values="salary",
aggregate_function="first",
)
print(wide)
long = wide.unpivot(
index="name",
variable_name="dept",
value_name="salary",
)
print(long)
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "sales.csv"
path.write_text("region,amount\nwest,10\neast,20\nwest,5\n")
query = (
pl.scan_csv(path)
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
)
print(query.explain())
print(query.collect().sort("region"))Reshaping with `pivot` and `unpivot`
pivot turns distinct values into columns. It is useful for reports, but it needs an aggregation when multiple rows share the same index and column pair. unpivot reverses this wide layout into key-value rows.
The Lazy API and CSV Scans
scan_csv creates a LazyFrame, which records operations without executing them. collect() runs the query and returns a DataFrame. This lets Polars optimize the complete operation before reading the file.
explain() displays the planned query. Look for filters and column selection being pushed toward the file scan. Reading less data usually improves performance.
Keeping Work Native
Prefer expressions such as pl.col("amount") * 1.2, string namespaces, and when().then().otherwise() over Python callbacks. Functions passed to map_elements or similar UDFs often run once per value, limiting optimization and adding Python overhead.
Exercise
Which method should execute a lazy query, and which method helps inspect its plan?
Show answer
Call collect() to execute it. Call explain() to inspect the plan.