Polars
Polars is a fast DataFrame library with no index, strict dtypes and a lazy query optimizer. This page covers the expression API, grouping, joins, windows, the lazy API and file IO, with examples on the course tables data/sales.csv, data/stores.csv and data/products.csv. Every runnable block uses Polars 2.1.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| fix the table display | pl.Config.set_* |
pl.Config.set_tbl_width_chars(100) |
| read a CSV with dates | pl.read_csv(..., try_parse_dates=True) |
pl.read_csv("data/sales.csv", try_parse_dates=True) |
| read a big file lazily | pl.scan_csv, pl.scan_parquet |
pl.scan_parquet("lake/*.parquet") |
| see column names and dtypes | df.schema, lf.collect_schema() |
df.schema["order_date"] |
| pick columns | df.select(...) |
df.select("order_id", "revenue") |
| pick columns by dtype or name pattern | selectors | df.select(cs.numeric()), cs.starts_with("unit") |
| add or replace a column | df.with_columns(...) |
df.with_columns(net=pl.col("revenue") * 0.9) |
| keep rows | df.filter(...) |
df.filter(pl.col("discount") > 0, pl.col("region") == "East") |
| a constant value | pl.lit(v) |
pl.lit("bulk") |
| if / elif / else | pl.when().then().otherwise() |
pl.when(c).then(pl.lit("a")).otherwise(pl.lit("b")) |
| map values with a dict | .replace(d), .replace_strict(d) |
pl.col("region").replace({"East": "E"}) |
| change a dtype | .cast(dtype) |
pl.col("quantity").cast(pl.Float64) |
| fill or drop nulls | .fill_null(v), df.drop_nulls() |
pl.col("discount").fill_null(0) |
| sort with a tie-breaker | df.sort(a, b, descending=[...]) |
df.sort("revenue", "order_id", descending=[True, False]) |
| largest N rows | df.top_k(n, by=) |
df.top_k(3, by="revenue") |
| one row per key | df.unique(subset=, keep=) |
df.unique("customer_id", keep="first", maintain_order=True) |
| aggregate per group | df.group_by(k).agg(...) |
df.group_by("region").agg(pl.col("revenue").sum()) |
| keep the order of first appearance | maintain_order=True |
df.group_by("region", maintain_order=True) |
| count rows per group | pl.len() |
.agg(lines=pl.len()) |
| count values | s.value_counts(sort=True) |
sales["channel"].value_counts(sort=True) |
| group value on every row | .over(keys) |
pl.col("revenue").sum().over("region") |
| rank inside groups | .rank(...).over(...) |
pl.col("revenue").rank("ordinal", descending=True).over("region") |
| running total in time order | .cum_sum().over(k, order_by=) |
pl.col("revenue").cum_sum().over("store_id", order_by="order_date") |
| time buckets | .dt.truncate("1mo"), group_by_dynamic |
group_by(month=pl.col("order_date").dt.truncate("1mo")) |
| join tables | df.join(o, 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") |
| prove the join keys are unique | validate="m:1" |
sales.join(products, on="product_id", validate="m:1") |
| nearest earlier match | df.join_asof(o, on=, by=) |
prices.join_asof(rates, on="date") |
| long → wide / wide → long | df.pivot(...) / df.unpivot(...) |
df.pivot(on="channel", index="region", values="units") |
| stack tables | pl.concat([a, b]) |
pl.concat([a, b], how="diagonal") |
| flatten nested JSON | .explode() and .unnest() |
df.explode("customers").unnest("customers") |
| see the optimized plan | lf.explain() |
print(lf.explain()) |
| run a lazy query | lf.collect() |
lf.collect() |
| write without loading all rows | lf.sink_parquet(path) |
lf.sink_parquet("sales_2024.parquet") |
| one value out of a frame | .item() |
df.select(pl.col("revenue").sum()).item() |
| compare two frames in a test | assert_frame_equal |
from polars.testing import assert_frame_equal |
| convert to / from pandas | df.to_pandas(), pl.from_pandas(pdf) |
pl.from_pandas(pdf) |
| hand features to scikit-learn | df.to_numpy() |
X = df.select("quantity", "discount").to_numpy() |
| run SQL on a frame | df.sql(...) |
sales.sql("SELECT region, count(*) FROM self GROUP BY 1") |
Setup and display
Section titled “Setup and display”Polars draws tables with box borders. Its defaults depend on the terminal, so fix them once at the top of a script or notebook.
import polars as plimport polars.selectors as cs
pl.Config.set_tbl_rows(8) # at most 8 rows (first 4, …, last 4)pl.Config.set_tbl_cols(8) # at most 8 columnspl.Config.set_tbl_width_chars(100) # never wider than 100 characterspl.Config.set_fmt_str_lengths(30) # show up to 30 characters of textpl.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)print(sales.schema["order_date"], sales.schema["quantity"], sales.schema["revenue"])(20228, 13) (12, 5) (30, 6)Date Int64 Float64| Setting | Effect |
|---|---|
set_tbl_rows(n) |
rows shown; -1 shows all |
set_tbl_cols(n) |
columns shown; hidden columns become one … column |
set_tbl_width_chars(n) |
maximum table width; long cells wrap |
set_fmt_str_lengths(n) |
characters shown per text cell |
set_fmt_float("full") |
every digit, never 3.5965e6 |
set_tbl_hide_dataframe_shape(True) |
drop the shape: (r, c) line |
with pl.Config(tbl_rows=20): |
change settings for one block only |
Data model
Section titled “Data model”| Object | What it is | Made by |
|---|---|---|
pl.Series |
one named, typed column | pl.Series("x", [1, 2]), df["x"], df.get_column("x") |
pl.DataFrame |
columns of equal length; no index | pl.DataFrame(dict), pl.read_csv, pl.from_pandas |
pl.LazyFrame |
a query plan; no data until collect() |
pl.scan_csv, df.lazy() |
pl.Expr |
a recipe for a column, run inside a context | pl.col("x") * 2, pl.len(), pl.lit(0) |
| Dtype | Prints as | Notes |
|---|---|---|
pl.String |
str |
UTF-8 text (pl.Utf8 is an alias) |
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("min") (the default rank() is f64) |
pl.Float64 |
f64 |
NaN is a float value; null means missing |
pl.Boolean |
bool |
the mean is the share of true |
pl.Date, pl.Datetime("us"), pl.Duration |
date, datetime[μs], duration[μs] |
b - a gives a Duration |
pl.Enum([...]), pl.Categorical |
enum, cat |
fixed list of values / values learned from data |
pl.List(inner), pl.Struct(fields) |
list[...], struct[n] |
.list and .struct namespaces |
Expressions
Section titled “Expressions”An expression describes a column. It does nothing until a context runs it, so you can store it in a variable and reuse it. Polars runs the expressions of one context in parallel.
| Context | Returns | Example |
|---|---|---|
df.select(e, name=e) |
only the listed columns | df.select("region", net=pl.col("revenue") * 0.9) |
df.with_columns(e, name=e) |
all columns plus new or replaced ones | df.with_columns(pl.col("product").str.to_uppercase()) |
df.filter(p1, p2) |
rows where every predicate is true | df.filter(pl.col("quantity") > 2) |
df.group_by(k).agg(e) |
one row per group | df.group_by("region").agg(pl.col("revenue").mean()) |
df.sort(e) |
the same rows, reordered | df.sort(pl.col("product").str.len_chars()) |
Selecting columns
Section titled “Selecting columns”| Code | Selects |
|---|---|
"a", pl.col("a") |
one column (a string works in select, group_by, sort) |
pl.col("a", "b") |
several columns; the expression runs on each |
pl.col(pl.Float64), pl.col(pl.Int64, pl.Float64) |
every column of these dtypes |
pl.col("^unit_.*$") |
a regular expression (must start with ^ and end with $) |
pl.all(), pl.all().exclude("id") |
every column, or every column but some |
pl.first(), pl.last(), pl.nth(2) |
by position |
cs.numeric(), cs.string(), cs.temporal(), cs.by_dtype(pl.Date) |
selectors by dtype |
cs.starts_with("unit"), cs.ends_with("_id"), cs.contains("date") |
selectors by name |
cs.string() - cs.by_name("order_id") |
combine selectors with |, &, -, ~ |
.name.suffix("_z"), .name.prefix("log_") |
rename the outputs of a multi-column expression |
Expression catalog
Section titled “Expression catalog”| Expression | Meaning |
|---|---|
+ - * / // % ** |
arithmetic, element by element |
== != < <= > >= |
comparison → Boolean |
(a > 0) & (b > 0), |, ~ |
and, or, not (parentheses required) |
.is_in([...]), .is_between(lo, hi) |
membership, inclusive range |
.is_null(), .is_not_null(), .fill_null(v), .fill_null(strategy="forward") |
missing values |
.is_nan(), .fill_nan(v) |
float NaN (not the same as null) |
.cast(pl.Int32), .cast(pl.Int32, strict=False) |
change dtype; strict=False turns failures into null |
.alias("name") |
name the result (same as name=expr in a context) |
.round(2), .abs(), .clip(0, 100), .log(), .sqrt() |
numeric helpers |
.sum(), .mean(), .median(), .std(), .quantile(0.9), .n_unique() |
reduce to one value |
.shift(1), .diff(), .pct_change() |
compare with an earlier row (sort first) |
.cum_sum(), .cum_max(), .cum_count() |
running values |
.rolling_mean(7), .rolling_sum(7, min_samples=1) |
trailing windows over rows |
.rank("dense", descending=True) |
rank; methods average, min, max, dense, ordinal |
.filter(cond) |
keep some values (inside agg or select) |
.sort_by("y"), .first(), .last() |
order values, then pick |
pl.when(c1).then(a).when(c2).then(b).otherwise(d) |
conditional value; first true branch wins |
pl.format("{}-{}", a, b), pl.concat_str([a, b], separator="-") |
build text |
pl.date(2024, 1, 1), pl.duration(days=7) |
date and duration literals |
.str method |
Does |
|---|---|
to_uppercase(), to_lowercase(), to_titlecase() |
change case |
strip_chars(), strip_chars_start("0") |
remove spaces or given characters |
len_chars(), slice(0, 3), head(3) |
length, substring |
contains(p), contains(s, literal=True), starts_with(s), ends_with(s) |
tests (contains uses regex by default) |
replace(p, r), replace_all(p, r) |
replace the first / every match |
extract(r"(\d+)", 1), extract_all(r"\d+") |
regex groups |
split(" "), join("-") |
text → list column; column → one string |
to_date("%d/%m/%Y"), to_datetime(fmt), to_integer() |
parse text |
.dt method |
Does |
|---|---|
year(), quarter(), month(), day(), hour() |
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"), month_end() |
calendar arithmetic |
total_days(), total_hours() |
on a Duration |
Period strings: "1d", "1w", "1mo", "1q", "1y", "1h", "15m", "30s".
select, with_columns, filter
Section titled “select, with_columns, filter”gross = pl.col("unit_price") * pl.col("quantity") # a recipe, reusablereport = ( sales.with_columns(gross=gross) # all columns + gross .with_columns(saved=(pl.col("gross") - pl.col("revenue")).round(2)) # uses gross .filter(pl.col("channel") == "online", pl.col("discount") >= 0.15) # comma = AND .select( "order_id", "category", "saved", size=pl.when(pl.col("quantity") >= 3) .then(pl.lit("bulk")) .otherwise(pl.lit("single")), ) .sort("saved", "order_id", descending=[True, False]) # order_id breaks ties .head(4))print(report)shape: (4, 4)┌──────────┬─────────────┬───────┬────────┐│ order_id ┆ category ┆ saved ┆ size ││ --- ┆ --- ┆ --- ┆ --- ││ str ┆ str ┆ f64 ┆ str │╞══════════╪═════════════╪═══════╪════════╡│ O014571 ┆ Electronics ┆ 779.4 ┆ bulk ││ O013545 ┆ Electronics ┆ 519.6 ┆ single ││ O005024 ┆ Electronics ┆ 459.6 ┆ single ││ O008251 ┆ Electronics ┆ 459.6 ┆ single │└──────────┴─────────────┴───────┴────────┘print(sales.select(cs.numeric().max()).row(0)) # one expression, 4 columnsprint(sales.select(cs.string() - cs.ends_with("_id")).columns)print(sales.select(pl.col("revenue").sum().round(2), lines=pl.len()).rows())(1299.0, 25, 0.2, 5196.0)['region', 'channel', 'product', 'category'][(3596523.83, 20228)]group_by and aggregation
Section titled “group_by and aggregation”Group order is not stable between runs. maintain_order=True keeps the order in which each key first appears; .sort(...) gives a fixed order of your choice.
by_region = sales.group_by("region", maintain_order=True).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=pl.col("revenue").filter(pl.col("revenue") > 1000).len(), top_product=pl.col("product").sort_by("revenue").last(),)print(by_region)shape: (4, 7)┌────────┬───────────┬───────┬────────┬──────────────┬─────┬──────────────────────────┐│ region ┆ revenue ┆ lines ┆ orders ┆ online_share ┆ big ┆ top_product ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ str ┆ f64 ┆ u32 ┆ u32 ┆ f64 ┆ u32 ┆ str │╞════════╪═══════════╪═══════╪════════╪══════════════╪═════╪══════════════════════════╡│ West ┆ 822844.57 ┆ 4722 ┆ 3497 ┆ 0.413 ┆ 220 ┆ 14-inch Ultrabook Laptop ││ South ┆ 891766.07 ┆ 5144 ┆ 3766 ┆ 0.413 ┆ 234 ┆ 14-inch Ultrabook Laptop ││ East ┆ 993683.72 ┆ 5396 ┆ 4002 ┆ 0.422 ┆ 284 ┆ 14-inch Ultrabook Laptop ││ North ┆ 888229.47 ┆ 4966 ┆ 3612 ┆ 0.432 ┆ 231 ┆ 55-inch 4K Smart TV │└────────┴───────────┴───────┴────────┴──────────────┴─────┴──────────────────────────┘monthly = ( sales.group_by(month=pl.col("order_date").dt.truncate("1q")) # a key expression .agg(pl.col("revenue").sum().round(0)) .sort("month"))print(monthly.head(3))print(sales.group_by("channel").len().sort("channel").rows()) # rows per groupshape: (3, 2)┌────────────┬─────────┐│ month ┆ revenue ││ --- ┆ --- ││ date ┆ f64 │╞════════════╪═════════╡│ 2023-01-01 ┆ 291278 ││ 2023-04-01 ┆ 383639 ││ 2023-07-01 ┆ 412017 │└────────────┴─────────┘[('online', 8495), ('store', 11733)]| Aggregation | Meaning |
|---|---|
pl.len() |
rows in the group |
pl.col("x").count() |
non-null values |
sum(), mean(), median(), min(), max(), std(), quantile(q) |
statistics; nulls are skipped |
n_unique() |
distinct values |
first(), last() |
first / last value in row order |
pl.col("x").filter(cond).sum() |
aggregate only the rows that pass cond |
pl.col("x").sort_by("y").last() |
the x of the row with the largest y |
pl.col("x") alone, or implode() |
every value of the group as a List |
pl.col("a", "b").sum() |
one aggregation on several columns |
| Grouping helper | Use |
|---|---|
group_by("a", "b") |
several keys |
group_by(year=pl.col("d").dt.year()) |
a computed key with a name |
group_by(...).len(); .first(), .mean() |
rows per group; one aggregation of every column |
group_by_dynamic("d", every="1mo") |
calendar windows on a sorted date column |
rolling(index_column="d", period="7d") |
a trailing time window per row |
partition_by("region", as_dict=True) |
split into one frame per key |
Window expressions with over
Section titled “Window expressions with over”expr.over(keys) computes expr per group and puts the result back on every row of that group, like groupby().transform() in pandas or OVER (PARTITION BY ...) in SQL. The row count does not change.
daily = sales.group_by("store_id", "order_date").agg(pl.col("revenue").sum().round(2))windows = daily.with_columns( share=(pl.col("revenue") / pl.col("revenue").sum().over("store_id")).round(4), rank=pl.col("revenue").rank("min", descending=True).over("store_id"), cum=pl.col("revenue").cum_sum().over("store_id", order_by="order_date").round(2), prev=pl.col("revenue").shift(1).over("store_id", order_by="order_date"),)print(windows.filter(pl.col("store_id") == "S01").sort("order_date").head(4))shape: (4, 7)┌──────────┬────────────┬─────────┬────────┬──────┬─────────┬─────────┐│ store_id ┆ order_date ┆ revenue ┆ share ┆ rank ┆ cum ┆ prev ││ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ││ str ┆ date ┆ f64 ┆ f64 ┆ u32 ┆ f64 ┆ f64 │╞══════════╪════════════╪═════════╪════════╪══════╪═════════╪═════════╡│ S01 ┆ 2023-01-01 ┆ 1227.43 ┆ 0.003 ┆ 95 ┆ 1227.43 ┆ null ││ S01 ┆ 2023-01-03 ┆ 153.99 ┆ 0.0004 ┆ 468 ┆ 1381.42 ┆ 1227.43 ││ S01 ┆ 2023-01-04 ┆ 143.5 ┆ 0.0004 ┆ 477 ┆ 1524.92 ┆ 153.99 ││ S01 ┆ 2023-01-06 ┆ 549.44 ┆ 0.0014 ┆ 232 ┆ 2074.36 ┆ 143.5 │└──────────┴────────────┴─────────┴────────┴──────┴─────────┴─────────┘| Pattern | Code |
|---|---|
| group total on every row | pl.col("x").sum().over("k") |
| share of the group | pl.col("x") / pl.col("x").sum().over("k") |
| rank inside the 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") |
| previous value in the group | pl.col("x").shift(1).over("k", order_by="date") |
| first row per group | df.filter(pl.col("date") == pl.col("date").min().over("k")) |
| several keys | .over("region", "channel") |
| one list per group | .over("k", mapping_strategy="join") |
| grand total (no keys) | pl.col("x").sum() in with_columns broadcasts |
targets = pl.DataFrame({"store_id": ["S01", "S07", "S13"], "target": [4, 5, 1]})for how in ["inner", "left", "full", "semi", "anti"]: j = targets.join(stores, on="store_id", how=how, coalesce=True) print(f"{how:<5} rows={j.height:>2} cols={j.width}", sorted(j["store_id"])[-3:])inner rows= 2 cols=6 ['S01', 'S07']left rows= 3 cols=6 ['S01', 'S07', 'S13']full rows=13 cols=6 ['S11', 'S12', 'S13']semi rows= 2 cols=2 ['S01', 'S07']anti rows= 1 cols=2 ['S13']how= |
Rows | Columns | SQL |
|---|---|---|---|
"inner" (default) |
keys in both | both | INNER JOIN |
"left", "right" |
every row of one side | both; nulls where no match | LEFT JOIN, RIGHT JOIN |
"full" |
every row of both | both; coalesce=True merges the keys |
FULL OUTER JOIN |
"semi" |
left rows with a match, once each | left only | WHERE EXISTS |
"anti" |
left rows without a match | left only | WHERE NOT EXISTS |
"cross" |
every pair (no on) |
both | CROSS JOIN |
| Option | Use |
|---|---|
on="k", on=["a", "b"], left_on=, right_on= |
key columns, same or different names |
validate="m:1", "1:1", "1:m" |
raise ComputeError when keys are not unique as stated |
maintain_order="left" |
keep the left row order (default: no guaranteed order) |
suffix="_store" |
rename clashing right columns (default _right) |
coalesce=True |
one key column instead of k and k_right (outer joins) |
nulls_equal=True |
let null keys match each other |
df.join_asof(o, on="date", by="k", strategy="backward") |
nearest earlier key; both frames sorted by on |
df.join_where(o, pl.col("d") >= pl.col("start")) |
join on inequality predicates |
dup = pl.concat([stores, stores.head(1)]) # S01 twicesales.join(dup, on="store_id", validate="m:1") # stops the fan-outpolars.exceptions.ComputeError: join keys did not fulfill m:1 validationLazy API
Section titled “Lazy API”pl.scan_* and df.lazy() return a LazyFrame: a query plan. collect() hands the plan to the optimizer, then runs it. In Polars 2, collect() uses the streaming engine by default, which processes data in batches.
query = ( pl.scan_csv("data/sales.csv", try_parse_dates=True) .filter(pl.col("order_date").dt.year() == 2024) .group_by("category") .agg(revenue=pl.col("revenue").sum().round(2)) .sort("revenue", descending=True))print(type(query).__name__, query.collect_schema())plan = query.explain() # read it from the bottom upprint([x.strip() for x in plan.splitlines() if "PROJECT" in x or "SELECTION" in x])print(query.head(3).collect().rows())LazyFrame Schema({'category': String, 'revenue': Float64})['PROJECT 3/13 COLUMNS', 'SELECTION: (col("order_date").dt.year() == 2024)'][('Electronics', 939924.77), ('Home', 397844.84), ('Sports', 299576.31)]| Step | Call |
|---|---|
| start lazy | pl.scan_csv(p), pl.scan_parquet("dir/*.parquet"), pl.scan_ndjson(p), df.lazy() |
| output columns, no work | lf.collect_schema(), lf.collect_schema().names() |
| optimized / written plan | lf.explain() / lf.explain(optimized=False) |
| run | lf.collect(); engine="auto" (the default) picks streaming; also "in-memory", "gpu" |
| peek at a few rows | lf.head(5).collect() |
| run several plans at once | pl.collect_all([lf1, lf2]) |
| write without collecting | lf.sink_parquet(p), lf.sink_csv(p), lf.sink_ndjson(p) |
| reuse an eager frame | df.lazy()...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 |
| slice pushdown: stop after N rows | SLICE: ... len: 5 in the scan after head(5) |
| common subplan elimination | one shared CACHE for a frame used twice |
( pl.scan_csv("data/sales.csv", try_parse_dates=True) .filter(pl.col("region") == "West") .sink_parquet("west.parquet") # streams to disk; returns None)west = pl.scan_parquet("west.parquet")print(west.select(pl.len(), pl.col("revenue").sum().round(2)).collect().row(0))(4722, 822844.57)Reading and writing
Section titled “Reading and writing”| Format | Eager read | Lazy read | Write |
|---|---|---|---|
| CSV | pl.read_csv(p) |
pl.scan_csv(p) |
df.write_csv(p), lf.sink_csv(p) |
| Parquet | pl.read_parquet(p) |
pl.scan_parquet(p) |
df.write_parquet(p), lf.sink_parquet(p) |
| JSON (one document) | pl.read_json(p) |
— | df.write_json(p) |
| NDJSON (one object per line) | pl.read_ndjson(p) |
pl.scan_ndjson(p) |
df.write_ndjson(p) |
| Arrow IPC / Feather | pl.read_ipc(p) |
pl.scan_ipc(p) |
df.write_ipc(p) |
| Excel | pl.read_excel(p) (needs fastexcel; engine="openpyxl" also works) |
— | df.write_excel(p) (needs xlsxwriter) |
| database | pl.read_database(sql, connection=con) |
— | df.write_database("t", connection) |
| Python objects | pl.DataFrame(dict), pl.from_dicts(rows), pl.from_pandas(pdf) |
— | df.to_dicts(), df.rows(), df.to_pandas() |
read_csv / scan_csv option |
Use |
|---|---|
try_parse_dates=True |
ISO date text → Date / Datetime |
schema_overrides={"zip": pl.String} |
force the dtype of some columns |
null_values=["", "N/A", "-"] |
tokens that mean missing |
columns=["a", "b"], n_rows=1000 |
read some columns / the first rows only |
infer_schema_length=10_000 |
infer dtypes from more rows (default 100) |
separator=";", decimal_comma=True, encoding="latin1" |
European and legacy files |
glob=True (default) |
"data/reports/*.csv" reads every match as one table (same column order) |
include_file_paths="source" |
add a column with the file each row came from |
import sqlite3
raw = pl.read_json("data/customers.json") # one document with a nested listpeople = raw.select(pl.col("customers").explode()).unnest("customers")print(raw.columns, people.shape)city = pl.col("address").struct.field("city") # a field of a Struct columnprint(people.select("customer_id", "plan", city=city).head(2))
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True) # read-onlysql = "SELECT region, COUNT(*) AS n FROM stores GROUP BY region ORDER BY region"print(pl.read_database(sql, connection=con).rows())con.close()['exported_at', 'count', 'customers'] (20, 9)shape: (2, 3)┌─────────────┬──────────┬─────────┐│ customer_id ┆ plan ┆ city ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ str │╞═════════════╪══════════╪═════════╡│ C00001 ┆ premium ┆ Chicago ││ C00002 ┆ standard ┆ Denver │└─────────────┴──────────┴─────────┘[('East', 3), ('North', 3), ('South', 3), ('West', 3)]pandas ↔ Polars
Section titled “pandas ↔ Polars”| pandas | Polars |
|---|---|
pd.read_csv(p, parse_dates=["d"]) |
pl.read_csv(p, try_parse_dates=True) |
df.head(), df.shape, df.dtypes |
df.head(), df.shape, df.schema |
df.describe() |
df.describe() |
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.loc[mask, ["a", "b"]] |
df.filter(mask).select("a", "b") |
df.iloc[0], df.iloc[:5] |
df.row(0), df.head(5) / df[:5] |
df.assign(c=df["a"] * 2), df["c"] = ... |
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), np.select(...) |
pl.when(c).then(x).otherwise(y), chained .when() |
df.rename(columns={"a": "b"}) |
df.rename({"a": "b"}) |
df.drop(columns=["a"]) |
df.drop("a") |
df.astype({"a": "float64"}) |
df.with_columns(pl.col("a").cast(pl.Float64)) |
df.sort_values("a", ascending=False) |
df.sort("a", descending=True) |
df.nlargest(3, "a") |
df.top_k(3, by="a") |
df.drop_duplicates("k") |
df.unique("k", keep="first", maintain_order=True) |
df.groupby("k").agg(t=("a", "sum")) |
df.group_by("k").agg(t=pl.col("a").sum()) |
df.groupby("k").size() |
df.group_by("k").len() |
df.groupby("k")["a"].transform("mean") |
pl.col("a").mean().over("k") |
df.groupby("k")["a"].cumsum() |
pl.col("a").cum_sum().over("k") |
df.groupby("k")["a"].shift() |
pl.col("a").shift().over("k") |
df["a"].rolling(7).mean() |
pl.col("a").rolling_mean(7) |
df.resample("MS", on="d").sum() |
df.group_by_dynamic("d", every="1mo").agg(...) |
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.merge(o, how="outer") |
df.join(o, on="k", how="full", coalesce=True) |
pd.concat([a, b]) |
pl.concat([a, b]) (how="diagonal" for different columns) |
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 (Monday = 0) |
pl.col("d").dt.weekday() - 1 |
pd.cut(x, bins) |
pl.when chain; cut is deprecated in Polars 2 |
df.isna().sum() |
df.null_count() |
df.fillna(0), df.dropna() |
df.fill_null(0), df.drop_nulls() |
df.ffill() |
df.fill_null(strategy="forward") |
df.set_index("k"), df.reset_index() |
not needed: there is no index |
df.apply(f, axis=1) |
an expression; map_elements only as a last resort |
df.to_numpy() |
df.to_numpy() |
import pandas as pd
pdf = products.head(3).select("product_id", "unit_price").to_pandas() # needs pyarrowprint(type(pdf).__name__, pdf.dtypes.astype(str).tolist())back = pl.from_pandas(pdf)print(back.schema)DataFrame ['str', 'float64']Schema({'product_id': String, 'unit_price': Float64})Polars 2 changes
Section titled “Polars 2 changes”Many tutorials still show Polars 0.x or 1.x code. In Polars 2 most old names raise an error that names the replacement.
| Old code | Polars 2 | What the old code does now |
|---|---|---|
df.groupby(...) |
df.group_by(...) |
AttributeError |
df.melt(id_vars=...) |
df.unpivot(index=..., on=...) |
AttributeRemovedError |
df.with_row_count() |
df.with_row_index() (column index, not row_nr) |
AttributeRemovedError |
pl.count() for rows |
pl.len(); pl.count("x") counts non-null values |
TypeError |
df.group_by(k).count() |
df.group_by(k).len() |
AttributeRemovedError |
df.frame_equal(o) |
df.equals(o) |
AttributeError |
.apply(f), .map_dict(d) |
.map_elements(f, return_dtype=...), .replace(d) / .replace_strict(d) |
AttributeError |
.where(cond) on an expression |
.filter(cond) |
AttributeRemovedError |
.flatten() |
.list.explode() |
AttributeRemovedError |
.str.strip() |
.str.strip_chars() |
AttributeError |
.str.concat("-") |
.str.join("-") (default separator "") |
AttributeRemovedError |
rolling_mean(7, min_periods=1) |
rolling_mean(7, min_samples=1) |
ArgumentRemovedError |
how="outer" |
how="full" |
ValueError |
join_nulls=True |
nulls_equal=True |
ArgumentRemovedError |
pivot(columns=...) |
pivot(on=...) |
ArgumentRemovedError |
collect(streaming=True) |
collect(engine="streaming"); the default engine is now streaming |
ArgumentRemovedError |
lf.fetch(n) |
lf.head(n).collect() |
AttributeRemovedError |
lf.profile() |
removed; time collect() yourself |
AttributeRemovedError |
lf.with_context(o) |
pl.concat([a, b], how="horizontal") |
AttributeRemovedError |
pl.read_csv_batched(p) |
pl.scan_csv(p) + collect() |
AttributeRemovedError |
.dt.with_time_unit("ms") |
cast to pl.Int64, then to the new dtype |
AttributeRemovedError |
df.approx_n_unique() |
df.select(pl.all().approx_n_unique()) |
AttributeRemovedError |
.cut(breaks), .qcut(q) |
.bin_intervals(...), .bin_quantiles(...) (both experimental) |
DeprecationWarning |
pl.col("x").is_in(series) |
pl.col("x").is_in(series.implode()), or a list |
DeprecationWarning |
lf.columns, lf.schema |
lf.collect_schema().names(), lf.collect_schema() |
PerformanceWarning |
sales.melt(id_vars="order_id") # old tutorial codepolars.exceptions.AttributeRemovedError: `melt` was removed in version 2.0; use `DataFrame.unpivot` instead, with `index` instead of `id_vars` and `on` instead of `value_vars`Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
printing a group_by, unique or join result |
the row order changes between runs | .sort(...), maintain_order=True, or maintain_order="left" for joins |
a string in then("bulk") |
ColumnNotFoundError: unable to find column "bulk" |
then(pl.lit("bulk")); strings are column names |
a column used in the with_columns call that creates it |
ColumnNotFoundError |
chain a second with_columns |
pl.col("a") > 0 & pl.col("b") > 0 |
TypeError about the truth value of an Expr |
parentheses around each comparison, or commas in filter |
a CSV read without try_parse_dates=True |
dates are str; .dt raises InvalidOperationError |
try_parse_dates=True or .str.to_date(fmt) |
print(lazy_frame) |
a plan, not data | lf.collect() or lf.head(5).collect() |
collect() after every step |
slow; the optimizer sees only small pieces | build the whole chain, collect once |
sort("x").head(3) with ties in x |
the third row changes between runs | add a tie-breaker: sort("x", "id") |
rank() with ties for “top N” |
ranks like 1.5; <= 1 drops both tied rows |
rank("ordinal") or rank("min") |
shift, diff, pct_change without an order |
values compared across groups or in file order | .over("k", order_by="date"), or sort first |
df1 == df2 |
a frame of Booleans | df1.equals(df2) (ignores dtypes) or assert_frame_equal (checks them) |
| counts compared with pandas | dtype mismatch u32 vs int64 |
.cast(pl.Int64) before comparing |
| big floats | 3.5965e6 hides the cents |
pl.Config.set_fmt_float("full") and .round(2) |
map_elements for arithmetic |
PolarsInefficientMapWarning; a slow Python loop |
write an expression |
NaN vs null |
fill_null leaves NaN in a float column |
.fill_nan(None) first, or .fill_nan(0) |
.str.contains("1.5") |
. matches any character |
literal=True |
| join on a non-unique right key | rows multiply; totals inflate | validate="m:1", or aggregate the right side first |
| Parquet dates | sales_sample.parquet stores order_date as Datetime, not Date |
.dt.date() or .cast(pl.Date) |
| pivot output names | pl.col(2024) fails |
pivot column names are strings: pl.col("2024") |
| a glob of CSVs whose columns are in a different order | ComputeError: schema names differ |
pl.concat([pl.read_csv(f) for f in files], how="diagonal_relaxed") |
| tutorial code from Polars 0.x / 1.x | AttributeRemovedError, ArgumentRemovedError |
see Polars 2 changes |
Learn more
Section titled “Learn more”- Module 31 lesson: Polars and its cheat sheet
- Module 30: SQL for data analysis for the same ideas in SQL and DuckDB
- Module 24: pandas fundamentals and module 25: pandas advanced for the pandas side of the translation table
- Master cheat sheet: SQL and DuckDB