Skip to content

31. Polars — Cheat sheet

The essentials of module 31 on one page. Every runnable block on this page is checked against its output with Polars 2.1.

I want to… Use… Example
fix the table display pl.Config.set_* pl.Config.set_tbl_width_chars(100)
build a table pl.DataFrame(dict) pl.DataFrame({"id": ["S01"], "units": [3]})
read a CSV with dates pl.read_csv(..., try_parse_dates=True) pl.read_csv("data/sales.csv", try_parse_dates=True)
read a CSV lazily pl.scan_csv(...) pl.scan_csv("data/sales.csv")
read Parquet pl.read_parquet / pl.scan_parquet pl.read_parquet("data/sales_sample.parquet")
see the dtypes df.schema, lf.collect_schema() df.schema["order_date"]
pick columns df.select(...) df.select("order_id", "revenue")
add or replace columns df.with_columns(...) df.with_columns(net=pl.col("revenue") * 0.9)
keep rows df.filter(...) df.filter(pl.col("discount") > 0)
sort df.sort(..., descending=) df.sort("revenue", descending=True)
aggregate per group df.group_by(...).agg(...) df.group_by("region").agg(pl.col("revenue").sum())
keep group order fixed .sort(...) or maintain_order=True df.group_by("k", maintain_order=True)
count rows per group pl.len() .agg(lines=pl.len())
count distinct values .n_unique() pl.col("order_id").n_unique()
if / else per row pl.when().then().otherwise() pl.when(c).then(pl.lit("a")).otherwise(pl.lit("b"))
a constant column pl.lit(value) pl.lit("bulk")
text methods .str pl.col("product").str.to_uppercase()
date parts .dt pl.col("order_date").dt.month()
month key .dt.truncate("1mo") pl.col("order_date").dt.truncate("1mo")
group value on every row .over(keys) pl.col("revenue").sum().over("region")
rank inside groups .rank(...).over(...) pl.col("x").rank("ordinal", descending=True).over("k")
running total .cum_sum().over(..., order_by=) pl.col("x").cum_sum().over("k", order_by="date")
join tables df.join(other, on=, how=) sales.join(stores, on="store_id", how="left")
rows with / without a match how="semi" / how="anti" stores.join(sales, on="store_id", how="anti")
check join keys validate="m:1" sales.join(stores, on="store_id", validate="m:1")
long → wide df.pivot(on=, index=, values=) df.pivot(on="quarter", index="region", values="revenue")
wide → long df.unpivot(index=) df.unpivot(index="region")
run a lazy query lf.collect() lf.collect()
see the optimized plan lf.explain() print(lf.explain())
one value out of a table .item() df.select(pl.col("x").sum()).item()
compare two tables df.equals(other), assert_frame_equal df1.equals(df2)
convert to / from pandas df.to_pandas(), pl.from_pandas(pdf) pl.from_pandas(pdf)
hand data to scikit-learn df.to_numpy() X = df.select("a", "b").to_numpy()
run SQL on a DataFrame df.sql(...) or DuckDB df.sql("SELECT count(*) FROM self")
import polars as pl
pl.Config.set_tbl_rows(10) # at most 10 rows (first 5, …, last 5)
pl.Config.set_tbl_cols(8) # at most 8 columns (first 4, …, last 4)
pl.Config.set_tbl_width_chars(100) # never wider than 100 characters
pl.Config.set_fmt_str_lengths(30) # show up to 30 characters of text
pl.Config.set_fmt_float("full") # no scientific notation for big floats
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)
Output
(20228, 13) (12, 5) (30, 6)

with pl.Config(tbl_rows=20): print(df) changes a setting for one block only.

s = pl.Series("revenue", [66.49, None, 224.1])
print(s.dtype, s.len(), s.null_count(), s.sum())
df = pl.DataFrame({"store_id": ["S01", "S02"], "units": [3, 5]})
print(df.shape, df.height, df.width, df.columns)
print(df["units"].to_list(), df.row(0), df.to_dicts()[1])
Output
Float64 3 1 290.59
(2, 2) 2 2 ['store_id', 'units']
[3, 5] ('S01', 3) {'store_id': 'S02', 'units': 5}
Dtype Short name Notes
pl.String str UTF-8 text
pl.Int64, pl.Int32, pl.Int8 i64, i32, i8 .dt.year() is i32, .dt.month() is i8
pl.UInt32 u32 pl.len(), n_unique(), rank("ordinal")
pl.Float64 f64 NaN is a float value; null is “missing”
pl.Boolean bool the mean of a Boolean column is the share of true
pl.Date, pl.Datetime("us") date, datetime[μs] try_parse_dates=True, .str.to_date(fmt)
pl.Enum([...]) enum fixed list of values; rejects others; sorts in list order
pl.Categorical cat list of values learned from the data
pl.List(...), pl.Struct(...) list[...], struct[...] .list and .struct namespaces

Cast with pl.col("x").cast(pl.Float64). Missing values are null in every dtype: test with .is_null(), fill with .fill_null(0) or df.fill_null(...), drop with df.drop_nulls().

Task Eager Lazy
CSV pl.read_csv(path, try_parse_dates=True) pl.scan_csv(path, try_parse_dates=True)
Parquet pl.read_parquet(path) pl.scan_parquet("folder/*.parquet")
write CSV df.write_csv("output/x.csv") lf.sink_csv("output/x.csv")
write Parquet df.write_parquet("output/x.parquet") lf.sink_parquet("output/x.parquet")
read_csv option Use
try_parse_dates=True ISO date text → Date / Datetime
schema_overrides={"zip": pl.String} force dtypes for some columns
null_values=["", "N/A", "-"] tokens that mean missing
columns=["a", "b"] read only some columns
n_rows=1000 read the first rows only
infer_schema_length=10_000 infer dtypes from more rows (default 100)
gross = pl.col("unit_price") * pl.col("quantity") # a recipe, not data
out = (
sales.with_columns(gross=gross, is_online=pl.col("channel") == "online")
.filter(pl.col("is_online"), pl.col("discount") >= 0.1) # commas mean "and"
.select("order_id", "revenue", saved=(pl.col("gross") - pl.col("revenue")).round(2))
.sort("saved", "order_id", descending=[True, False]) # order_id breaks ties
.head(4)
)
print(out)
Output
shape: (4, 3)
┌──────────┬─────────┬───────┐
│ order_id ┆ revenue ┆ saved │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞══════════╪═════════╪═══════╡
│ O014571 ┆ 3117.6 ┆ 779.4 │
│ O013545 ┆ 2078.4 ┆ 519.6 │
│ O005024 ┆ 1838.4 ┆ 459.6 │
│ O008251 ┆ 1838.4 ┆ 459.6 │
└──────────┴─────────┴───────┘
Context Returns
select(e1, e2, name=e3) only the listed columns
with_columns(e1, name=e2) all columns plus new or replaced ones
filter(p1, p2) rows where every predicate is true
group_by(k).agg(e1, name=e2) one row per group
sort(c, descending=True) the same rows in a new order
Selecting columns Meaning
pl.col("a"), "a" one column
pl.col("a", "b") several columns; the expression runs on each
pl.col(pl.Float64) every column of a dtype
pl.all().exclude("id") every column except some
pl.col("^unit_.*$") a regular expression (starts with ^, ends with $)
import polars.selectors as cs; cs.numeric(), cs.string() selectors, combine with |, &, -
Expression Meaning
(a > 0) & (b > 0), |, ~ and, or, not (parentheses needed)
.is_in([...]), .is_between(lo, hi) membership, inclusive range
.is_null(), .fill_null(v), .drop_nulls() missing values
.alias("name") rename the result
.round(2), .abs(), .clip(0, 100) numeric helpers
.shift(1), .diff(), .pct_change() compare with the previous row (needs a sort)
.rolling_mean(7), .rolling_median(28) trailing windows (needs a sort)
pl.format("Q{}", e) build text from a template
pl.date(2024, 1, 1) a date literal
demo = products.select(
"product",
band=pl.when(pl.col("unit_price") < 30)
.then(pl.lit("budget"))
.when(pl.col("unit_price") < 150)
.then(pl.lit("mid"))
.otherwise(pl.lit("premium")),
code=pl.col("category").str.slice(0, 3).str.to_uppercase(),
launched=pl.col("launch_date").dt.strftime("%b %Y"),
).head(3)
print(demo)
Output
shape: (3, 4)
┌─────────────────────────────┬─────────┬──────┬──────────┐
│ product ┆ band ┆ code ┆ launched │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞═════════════════════════════╪═════════╪══════╪══════════╡
│ Wireless Earbuds ┆ mid ┆ ELE ┆ Mar 2021 │
│ Noise-Cancelling Headphones ┆ premium ┆ ELE ┆ Oct 2020 │
│ 55-inch 4K Smart TV ┆ premium ┆ ELE ┆ Sep 2021 │
└─────────────────────────────┴─────────┴──────┴──────────┘
.str Does
to_uppercase(), to_lowercase(), to_titlecase() change case
strip_chars(), strip_chars_start() remove spaces (or given characters)
len_chars() number of characters
contains(p), starts_with(s), ends_with(s) Boolean tests (contains uses regex unless literal=True)
replace(p, r), replace_all(p, r) replace the first / every match
slice(start, length) substring
split(" ") a List column
extract(r"(\d+)", 1) one regex group
to_date("%d/%m/%Y"), to_datetime(fmt) parse text dates
.dt Does
year(), quarter(), month(), day() date parts
weekday() Monday = 1 … Sunday = 7 (pandas: Monday = 0)
truncate("1mo"), truncate("1w") round down to the period start
strftime("%Y-%m") format as text
offset_by("1mo") add a calendar period
pl.col("b") - pl.col("a") a Duration; .dt.total_days()

Period strings: "1d", "1w", "1mo", "1q", "1y", "1h", "15m".

summary = (
sales.group_by("region")
.agg(
revenue=pl.col("revenue").sum().round(2),
lines=pl.len(),
orders=pl.col("order_id").n_unique(),
online_share=(pl.col("channel") == "online").mean().round(3),
big_lines=pl.col("revenue").filter(pl.col("revenue") > 1000).len(),
)
.sort("region")
)
print(summary)
Output
shape: (4, 6)
┌────────┬───────────┬───────┬────────┬──────────────┬───────────┐
│ region ┆ revenue ┆ lines ┆ orders ┆ online_share ┆ big_lines │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ u32 ┆ u32 ┆ f64 ┆ u32 │
╞════════╪═══════════╪═══════╪════════╪══════════════╪═══════════╡
│ East ┆ 993683.72 ┆ 5396 ┆ 4002 ┆ 0.422 ┆ 284 │
│ North ┆ 888229.47 ┆ 4966 ┆ 3612 ┆ 0.432 ┆ 231 │
│ South ┆ 891766.07 ┆ 5144 ┆ 3766 ┆ 0.413 ┆ 234 │
│ West ┆ 822844.57 ┆ 4722 ┆ 3497 ┆ 0.413 ┆ 220 │
└────────┴───────────┴───────┴────────┴──────────────┴───────────┘
Aggregation Meaning
sum(), mean(), median(), min(), max(), std() the usual statistics (skip nulls)
pl.len(), count() rows; non-null values
n_unique() distinct values
first(), last() first / last value (order matters)
quantile(0.9) 90th percentile
pl.col("x").filter(cond).sum() aggregate only some rows of each group
pl.col("x").sort_by("y").last() the x of the largest y per group
implode() all values of the group as a list

Keys can be expressions: group_by("channel", year=pl.col("order_date").dt.year()). For time buckets on a sorted date column, group_by_dynamic("order_date", every="1mo") is an alternative.

lines = sales.select(
"order_id",
"region",
"revenue",
order_share=(pl.col("revenue") / pl.col("revenue").sum().over("order_id")).round(3),
region_rank=pl.col("revenue").rank("min", descending=True).over("region"),
)
print(lines.filter(pl.col("order_id") == "O000004"))
Output
shape: (2, 5)
┌──────────┬────────┬─────────┬─────────────┬─────────────┐
│ order_id ┆ region ┆ revenue ┆ order_share ┆ region_rank │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ f64 ┆ u32 │
╞══════════╪════════╪═════════╪═════════════╪═════════════╡
│ O000004 ┆ West ┆ 59.99 ┆ 0.211 ┆ 2811 │
│ O000004 ┆ West ┆ 224.1 ┆ 0.789 ┆ 890 │
└──────────┴────────┴─────────┴─────────────┴─────────────┘
Pattern Code
group total on every row pl.col("x").sum().over("k")
share of group pl.col("x") / pl.col("x").sum().over("k")
rank in group pl.col("x").rank("ordinal", descending=True).over("k")
top N per group df.filter(pl.col("x").rank("ordinal", descending=True).over("k") <= 3)
running total in time order pl.col("x").cum_sum().over("k", order_by="date")
change from the previous row of a group pl.col("x").pct_change().over("k") (sort first)
first row of each group df.filter(pl.col("date") == pl.col("date").min().over("k"))

rank methods: "average" (default, ties get 1.5), "min", "max", "dense", "ordinal" (no ties).

query = (
pl.scan_csv("data/sales.csv")
.filter(pl.col("channel") == "store")
.group_by("region")
.agg(units=pl.col("quantity").sum())
.sort("region")
)
plan = query.explain()
print(
[
line.strip()
for line in plan.splitlines()
if "PROJECT" in line or "SELECTION" in line
]
)
print(query.collect()["units"].to_list())
Output
['PROJECT 3/13 COLUMNS', 'SELECTION: col("channel") == "store"']
[4530, 4133, 4378, 4044]
Step Call
start lazy pl.scan_csv(...), pl.scan_parquet(...), df.lazy()
see output columns lf.collect_schema()
see the optimized plan lf.explain(); unoptimized: lf.explain(optimized=False)
run lf.collect()
run in batches (big data) lf.collect(engine="streaming")
write without collecting lf.sink_parquet(path)
look at a few rows lf.head(5).collect()
Optimization Seen in explain() as
projection pushdown: read only used columns PROJECT 3/13 COLUMNS in the scan
predicate pushdown: filter while reading SELECTION: ... in the scan
join type change after a filter on the right side LEFT JOIN becomes INNER JOIN (Example 3 of the lesson prints it)
targets = pl.DataFrame({"store_id": ["S01", "S07", "S13"], "target": [4, 5, 1]})
for how in ["inner", "left", "semi", "anti"]:
joined = targets.join(stores, on="store_id", how=how).sort("store_id")
print(f"{how:<5}", joined.height, joined["store_id"].to_list(), joined.width)
Output
inner 2 ['S01', 'S07'] 6
left 3 ['S01', 'S07', 'S13'] 6
semi 2 ['S01', 'S07'] 2
anti 1 ['S13'] 2
how= Rows Columns
"inner" keys in both both tables
"left" all left rows both; nulls where no match
"right" all right rows both
"full" all rows of both (coalesce=True merges the keys) both
"semi" left rows with a match, once each left only
"anti" left rows without a match left only
"cross" every pair (no on) both
Option Use
on="k", left_on=, right_on= key columns (same or different names)
validate="m:1", "1:1", "1:m" raise ComputeError on unexpected duplicate keys
maintain_order="left" keep the left row order (default: no guaranteed order)
suffix="_b" name clashing right columns (default _right)
nulls_equal=True let null keys match each other

df.join_asof(other, on="date", by="store_id") matches each row with the nearest earlier or equal key (strategy="backward", the default; both tables sorted by date).

long = (
sales.group_by("region", "channel")
.agg(pl.col("quantity").sum())
.sort("region", "channel")
)
wide = long.pivot(on="channel", index="region", values="quantity")
print(wide)
print(wide.unpivot(index="region", variable_name="channel", value_name="units").shape)
Output
shape: (4, 3)
┌────────┬────────┬───────┐
│ region ┆ online ┆ store │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞════════╪════════╪═══════╡
│ East ┆ 3302 ┆ 4530 │
│ North ┆ 3179 ┆ 4133 │
│ South ┆ 3117 ┆ 4378 │
│ West ┆ 2850 ┆ 4044 │
└────────┴────────┴───────┘
(8, 3)
Need Call
long → wide df.pivot(on="col", index="row_key", values="cell")
several rows per cell add aggregate_function="sum" (or "mean", "len", …)
fixed column order sort before the pivot, or on_columns=[...]
lazy pivot lf.pivot(on=..., on_columns=[...], index=..., values=...)
wide → long df.unpivot(index="row_key", variable_name="col", value_name="cell")
stack tables pl.concat([a, b]); how="diagonal" fills missing columns with null
list column → rows df.explode("list_col")
pandas Polars
pd.read_csv(p, parse_dates=["d"]) pl.read_csv(p, try_parse_dates=True)
df["a"], df[["a", "b"]] df["a"], df.select("a", "b")
df[df["a"] > 0], df.query("a > 0") df.filter(pl.col("a") > 0)
df.assign(c=df["a"] * 2) df.with_columns(c=pl.col("a") * 2)
df.loc[mask, "a"] = 0 df.with_columns(a=pl.when(mask).then(0).otherwise(pl.col("a")))
np.where(c, x, y) pl.when(c).then(x).otherwise(y)
df.sort_values("a", ascending=False) df.sort("a", descending=True)
df.groupby("k").agg(t=("a", "sum")) df.group_by("k").agg(t=pl.col("a").sum())
df.groupby("k")["a"].transform("mean") pl.col("a").mean().over("k")
df["a"].value_counts() df["a"].value_counts(sort=True)
df.merge(o, on="k", how="left") df.join(o, on="k", how="left")
df.pivot_table(index="r", columns="c", values="v", aggfunc="sum") df.pivot(on="c", index="r", values="v", aggregate_function="sum")
df.melt(id_vars="k") df.unpivot(index="k")
df["s"].str.upper(), .str.strip() pl.col("s").str.to_uppercase(), .str.strip_chars()
df["d"].dt.day_of_week pl.col("d").dt.weekday() - 1
df.isna() df.select(pl.all().is_null())
df.isna().sum() df.null_count()
df.fillna(0), df.dropna() df.fill_null(0), df.drop_nulls()
df.reset_index() not needed: no index
len(df) df.height (or len(df))
df.apply(f, axis=1) an expression; map_elements only as a last resort
import pandas as pd
pdf = products.head(2).select("product_id", "unit_price").to_pandas()
print(type(pdf).__name__, list(pdf.dtypes.astype(str)))
back = pl.from_pandas(pdf)
print(back.schema, back.equals(products.head(2).select("product_id", "unit_price")))
print(products.select("unit_cost", "unit_price").to_numpy().shape)
print(
sales.sql(
"SELECT channel, count(*) AS n FROM self GROUP BY channel ORDER BY channel"
).rows()
)
Output
DataFrame ['str', 'float64']
Schema({'product_id': String, 'unit_price': Float64}) True
(30, 2)
[('online', 8495), ('store', 11733)]
From → to Call Needs
Polars → pandas df.to_pandas() pyarrow
pandas → Polars pl.from_pandas(pdf) (include_index=True keeps the index) pyarrow
Polars → NumPy df.to_numpy(), s.to_numpy() —
Polars → Python df.rows(), df.to_dicts(), s.to_list(), df.item() —
DuckDB → Polars duckdb.sql("... FROM df ...").pl() duckdb
Situation Choose
small data, plotting, statsmodels, the scikit-learn tutorials pandas
pipelines over large files, many cores, strict types Polars (lazy)
SQL-minded team, data in a database or Parquet folder DuckDB
larger than memory Polars streaming or DuckDB
model input prepare in Polars or DuckDB; to_numpy() / to_pandas() once
Old name (tutorials, Polars 0.x / 1.x) Polars 2
df.groupby(...) df.group_by(...)
df.melt(...) df.unpivot(...)
df.with_row_count() df.with_row_index()
pl.count() for row counts pl.len() (pl.count("col") counts non-null values)
df.frame_equal(other) df.equals(other)
.apply(f), .map_dict(d) .map_elements(f, return_dtype=...), .replace_strict(d)
.str.strip(), .str.concat() .str.strip_chars(), .str.join()
how="outer" how="full"
join_nulls=True nulls_equal=True
collect(streaming=True) collect(engine="streaming")
pivot(columns=...) pivot(on=...)
.cut(breaks) (deprecated) .bin_intervals(breaks, labels=[...], right_closed=True) (experimental; labels is required, and right_closed=True keeps the cut edges)
.qcut(...) (deprecated) .bin_quantiles(...) or .bin_ranks(...) (experimental)
  • Group, unique and join order is not guaranteed. Sort the result or pass maintain_order=True (maintain_order="left" for joins) before you print, compare or use shift, pct_change or head.
  • Strings in then() are column names. Use pl.lit("text") for constants. pl.when(c).then("bulk") raises ColumnNotFoundError.
  • One with_columns call cannot use a column it creates. Chain a second with_columns.
  • & and | bind tighter than >. Put every comparison in parentheses, or pass several predicates to filter with commas.
  • Dates stay text without try_parse_dates=True, and .dt then fails.
  • A LazyFrame is a plan. Printing it shows the plan; collect() runs it. Collect once, at the end.
  • df1 == df2 compares cell by cell. Use df1.equals(df2) for one Boolean; it ignores dtypes. assert_frame_equal checks dtypes too.
  • Big floats print in scientific notation (3.5965e6) by default. Set pl.Config.set_fmt_float("full") and round what you print.
  • map_elements is a slow Python loop and raises PolarsInefficientMapWarning when an expression could do the job.
  • Polars counts weekdays from 1 (Monday) and pandas from 0.
  • Counts are u32. pl.len() and n_unique() return UInt32; cast before comparing with pandas int64 in assert_frame_equal.
  • Ties make sort(...).head(n) unstable. Rows with equal sort keys can come out in any order. Add a tie-breaker column: sort("saved", "order_id", descending=[True, False]).
  • rank() gives ties the average rank (1.5). Pick "ordinal", "min" or "dense" for “top N”.
  • bin_intervals is not a drop-in cut. cut bins are right-closed ((30, 150]), bin_intervals bins are left-closed ([30, 150)) unless you pass right_closed=True. A plain swap moves the edge values to the next bin.
  • is_in with a Series of the same dtype is deprecated. pl.col("id").is_in(ids) raises a DeprecationWarning; write is_in(ids.implode()) or use a semi join.
  • Pivot column names are strings, even when the values were integers: pl.col("2024").