Skip to content

Polars

Polars builds every column operation from an expression such as pl.col("pvalue") < 0.05, and the same expression works on an in memory DataFrame or on a lazy query over a file. The page ran with Polars 2.1. Several calls from Polars 0.x and 1.x tutorials raise an error now, and the table near the end lists them. For a slower introduction, start with Polars Essentials.

Task Code
Select df.select("a", "b"), df.select(cs.numeric())
Filter df.filter(pl.col("p") < 0.05, pl.col("x") > 1)
Match a list pl.col("symbol").is_in(values)
Add columns df.with_columns(new=pl.col("x") * 2)
Row count in an expression pl.len()
Conditional column pl.when(cond).then(a).otherwise(b)
Per group value on each row pl.col("x").mean().over("g")
Sort df.sort("a", "b"), df.sort(expr, descending=True)
Group summary df.group_by("g").agg(n=pl.len()).sort("g")
Value at the best row pl.col("a").sort_by("p").first()
Counts df["col"].value_counts(), n_unique()
Ordered category pl.col("x").cast(pl.Enum(["low", "mid", "high"]))
Text to columns str.extract_groups(pattern) then unnest
One row per list item pl.col("x").str.split(";") then explode("x")
Join df.join(other, on="key", how="left")
Semi and anti join how="semi", how="anti"
Stack pl.concat([a, b], how="diagonal")
Flag repeats pl.col("key").is_duplicated()
One row per key df.unique(subset="key", keep="first", maintain_order=True)
Wide to long df.unpivot(index="id")
Long to wide df.pivot(on="sample", index="id", values="x")
Nulls null_count(), drop_nulls(), fill_null()
NaN is_nan(), fill_nan()
Lazy query pl.scan_csv(f), pl.scan_parquet(f)
Show the plan lf.explain()
Run lf.collect(), lf.collect(engine="streaming")
Write lazily lf.sink_parquet(f)
To pandas, NumPy df.to_pandas(), df.to_numpy()

This is the gene table from the pandas cheatsheet, built from the same seed, so the numbers match. The chromosome and the role are real for each gene. The fold changes, p-values, and mean counts are random.

import numpy as np
import polars as pl
rng = np.random.default_rng(42)
symbols = ["TP53", "BRCA1", "EGFR", "MYC", "KRAS", "PIK3CA", "PTEN",
"RB1", "APC", "VHL", "CDH1", "NF1", "BRAF", "IDH1", "CTNNB1",
"SMAD4", "ALK", "RET", "KIT", "MET"]
chromosomes = ["chr17", "chr17", "chr7", "chr8", "chr12", "chr3", "chr10",
"chr13", "chr5", "chr3", "chr16", "chr17", "chr7", "chr2",
"chr3", "chr18", "chr2", "chr10", "chr4", "chr7"]
suppressors = {"TP53", "BRCA1", "PTEN", "RB1", "APC", "VHL", "CDH1",
"NF1", "SMAD4"}
genes = pl.DataFrame({
"symbol": symbols,
"chromosome": chromosomes,
"role": ["suppressor" if s in suppressors else "oncogene"
for s in symbols],
"log2fc": rng.normal(0, 2, 20).round(2),
"pvalue": rng.uniform(0.0001, 0.2, 20).round(4),
"basemean": rng.uniform(50, 5000, 20).round(1),
})
print(genes.head())
shape: (5, 6)
┌────────┬────────────┬────────────┬────────┬────────┬──────────┐
│ symbol ┆ chromosome ┆ role ┆ log2fc ┆ pvalue ┆ basemean │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ f64 ┆ f64 ┆ f64 │
╞════════╪════════════╪════════════╪════════╪════════╪══════════╡
│ TP53 ┆ chr17 ┆ suppressor ┆ 0.61 ┆ 0.1516 ┆ 2213.9 │
│ BRCA1 ┆ chr17 ┆ suppressor ┆ -2.08 ┆ 0.071 ┆ 4171.8 │
│ EGFR ┆ chr7 ┆ oncogene ┆ 1.5 ┆ 0.1941 ┆ 3516.3 │
│ MYC ┆ chr8 ┆ oncogene ┆ 1.88 ┆ 0.1786 ┆ 1596.2 │
│ KRAS ┆ chr12 ┆ oncogene ┆ -3.9 ┆ 0.1557 ┆ 4169.7 │
└────────┴────────────┴────────────┴────────┴────────┴──────────┘
print(genes.shape)
for name, dtype in genes.schema.items():
print(f"{name:12s}{dtype}")
(20, 6)
symbol String
chromosome String
role String
log2fc Float64
pvalue Float64
basemean Float64
print(genes.select("symbol", "log2fc", "pvalue").head(3))
shape: (3, 3)
┌────────┬────────┬────────┐
│ symbol ┆ log2fc ┆ pvalue │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪════════╪════════╡
│ TP53 ┆ 0.61 ┆ 0.1516 │
│ BRCA1 ┆ -2.08 ┆ 0.071 │
│ EGFR ┆ 1.5 ┆ 0.1941 │
└────────┴────────┴────────┘

Selectors pick columns by type, and pl.col accepts a regex wrapped in ^ and $.

import polars.selectors as cs
print(genes.select(cs.numeric()).columns)
print(genes.select(cs.string()).columns)
print(genes.select(pl.col("^p.*$")).columns)
print(genes.select(pl.exclude("chromosome", "role")).columns)
['log2fc', 'pvalue', 'basemean']
['symbol', 'chromosome', 'role']
['pvalue']
['symbol', 'log2fc', 'pvalue', 'basemean']

Predicates passed as separate arguments are combined with AND.

sig = genes.filter(pl.col("pvalue") < 0.05, pl.col("log2fc").abs() > 1)
print(sig.select("symbol", "log2fc", "pvalue"))
shape: (3, 3)
┌────────┬────────┬────────┐
│ symbol ┆ log2fc ┆ pvalue │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪════════╪════════╡
│ PIK3CA ┆ -2.6 ┆ 0.039 │
│ SMAD4 ┆ -1.72 ┆ 0.038 │
│ KIT ┆ 1.76 ┆ 0.0455 │
└────────┴────────┴────────┘
panel = ["TP53", "KRAS", "EGFR", "BRAF"]
in_panel = genes.filter(pl.col("symbol").is_in(panel))
print(in_panel.select("symbol", "chromosome"))
print(genes.filter(pl.col("basemean").is_between(1000, 2000)).height)
shape: (4, 2)
┌────────┬────────────┐
│ symbol ┆ chromosome │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪════════════╡
│ TP53 ┆ chr17 │
│ EGFR ┆ chr7 │
│ KRAS ┆ chr12 │
│ BRAF ┆ chr7 │
└────────┴────────────┘
4

pl.len() is the row count inside an expression, which gives a Bonferroni correction in one line.

genes = genes.with_columns(
neg_log10p=-pl.col("pvalue").log10(),
p_bonf=(pl.col("pvalue") * pl.len()).clip(upper_bound=1.0),
)
smallest_p = genes.sort("pvalue").head(4)
print(smallest_p.select("symbol", "pvalue", "neg_log10p", "p_bonf"))
shape: (4, 4)
┌────────┬────────┬────────────┬────────┐
│ symbol ┆ pvalue ┆ neg_log10p ┆ p_bonf │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞════════╪════════╪════════════╪════════╡
│ RB1 ┆ 0.0089 ┆ 2.05061 ┆ 0.178 │
│ ALK ┆ 0.0261 ┆ 1.583359 ┆ 0.522 │
│ APC ┆ 0.0309 ┆ 1.510042 ┆ 0.618 │
│ SMAD4 ┆ 0.038 ┆ 1.420216 ┆ 0.76 │
└────────┴────────┴────────────┴────────┘

The expressions inside one with_columns call run side by side, so none of them can use a column another one creates. Chain a second with_columns for that.

when conditions are checked in order, and otherwise covers the rest.

up = (pl.col("log2fc") > 1) & (pl.col("pvalue") < 0.05)
down = (pl.col("log2fc") < -1) & (pl.col("pvalue") < 0.05)
genes = genes.with_columns(
direction=pl.when(up).then(pl.lit("up"))
.when(down).then(pl.lit("down"))
.otherwise(pl.lit("ns"))
)
labeled = genes.filter(pl.col("direction") != "ns")
print(labeled.select("symbol", "log2fc", "pvalue", "direction"))
shape: (3, 4)
┌────────┬────────┬────────┬───────────┐
│ symbol ┆ log2fc ┆ pvalue ┆ direction │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ str │
╞════════╪════════╪════════╪═══════════╡
│ PIK3CA ┆ -2.6 ┆ 0.039 ┆ down │
│ SMAD4 ┆ -1.72 ┆ 0.038 ┆ down │
│ KIT ┆ 1.76 ┆ 0.0455 ┆ up │
└────────┴────────┴────────┴───────────┘

.over() computes an expression per group and returns one value per row. It does the job of groupby().transform() in pandas.

role_mean = pl.col("log2fc").mean().over("role")
genes = genes.with_columns(
log2fc_vs_role=(pl.col("log2fc") - role_mean).round(2),
rank_in_role=pl.col("pvalue").rank("ordinal").over("role"),
)
cols = ["symbol", "role", "log2fc", "log2fc_vs_role", "rank_in_role"]
print(genes.select(cols).head(4))
shape: (4, 5)
┌────────┬────────────┬────────┬────────────────┬──────────────┐
│ symbol ┆ role ┆ log2fc ┆ log2fc_vs_role ┆ rank_in_role │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ f64 ┆ u32 │
╞════════╪════════════╪════════╪════════════════╪══════════════╡
│ TP53 ┆ suppressor ┆ 0.61 ┆ 0.83 ┆ 8 │
│ BRCA1 ┆ suppressor ┆ -2.08 ┆ -1.86 ┆ 4 │
│ EGFR ┆ oncogene ┆ 1.5 ┆ 1.44 ┆ 11 │
│ MYC ┆ oncogene ┆ 1.88 ┆ 1.82 ┆ 10 │
└────────┴────────────┴────────┴────────────────┴──────────────┘
by_role = genes.sort("role", "pvalue")
print(by_role.select("symbol", "role", "pvalue").head(4))
shape: (4, 3)
┌────────┬──────────┬────────┐
│ symbol ┆ role ┆ pvalue │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞════════╪══════════╪════════╡
│ ALK ┆ oncogene ┆ 0.0261 │
│ PIK3CA ┆ oncogene ┆ 0.039 │
│ KIT ┆ oncogene ┆ 0.0455 │
│ BRAF ┆ oncogene ┆ 0.0652 │
└────────┴──────────┴────────┘

Sort by an expression to rank genes by absolute fold change.

by_size = genes.sort(pl.col("log2fc").abs(), descending=True)
print(by_size.select("symbol", "log2fc").head(4))
shape: (4, 2)
┌────────┬────────┐
│ symbol ┆ log2fc │
│ --- ┆ --- │
│ str ┆ f64 │
╞════════╪════════╡
│ KRAS ┆ -3.9 │
│ PIK3CA ┆ -2.6 │
│ IDH1 ┆ 2.25 │
│ BRCA1 ┆ -2.08 │
└────────┴────────┘

group_by returns groups in no fixed order, so sort the result. sort_by inside agg picks the symbol with the smallest p-value in each group.

summary = (
genes.group_by("role")
.agg(
n_genes=pl.len(),
mean_log2fc=pl.col("log2fc").mean().round(2),
n_p05=(pl.col("pvalue") < 0.05).sum(),
top_gene=pl.col("symbol").sort_by("pvalue").first(),
)
.sort("role")
)
print(summary)
shape: (2, 5)
┌────────────┬─────────┬─────────────┬───────┬──────────┐
│ role ┆ n_genes ┆ mean_log2fc ┆ n_p05 ┆ top_gene │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 ┆ u32 ┆ str │
╞════════════╪═════════╪═════════════╪═══════╪══════════╡
│ oncogene ┆ 11 ┆ 0.06 ┆ 3 ┆ ALK │
│ suppressor ┆ 9 ┆ -0.22 ┆ 3 ┆ RB1 │
└────────────┴─────────┴─────────────┴───────┴──────────┘

Break the ties in value_counts with a second sort key, or the order can change between runs.

chrom_counts = genes["chromosome"].value_counts().sort(
["count", "chromosome"], descending=[True, False]
)
print(chrom_counts.head(4))
print(genes["chromosome"].n_unique())
shape: (4, 2)
┌────────────┬───────┐
│ chromosome ┆ count │
│ --- ┆ --- │
│ str ┆ u32 │
╞════════════╪═══════╡
│ chr17 ┆ 3 │
│ chr3 ┆ 3 │
│ chr7 ┆ 3 │
│ chr10 ┆ 2 │
└────────────┴───────┘
12
print(genes.select("log2fc", "pvalue", "basemean").describe())
shape: (9, 4)
┌────────────┬──────────┬──────────┬─────────────┐
│ statistic ┆ log2fc ┆ pvalue ┆ basemean │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪══════════╪══════════╪═════════════╡
│ count ┆ 20.0 ┆ 20.0 ┆ 20.0 │
│ null_count ┆ 0.0 ┆ 0.0 ┆ 0.0 │
│ mean ┆ -0.065 ┆ 0.098725 ┆ 2486.505 │
│ std ┆ 1.740419 ┆ 0.059069 ┆ 1372.388449 │
│ min ┆ -3.9 ┆ 0.0089 ┆ 86.4 │
│ 25% ┆ -1.71 ┆ 0.0455 ┆ 1477.2 │
│ 50% ┆ 0.26 ┆ 0.094 ┆ 2865.3 │
│ 75% ┆ 1.5 ┆ 0.149 ┆ 3540.6 │
│ max ┆ 2.25 ┆ 0.1941 ┆ 4171.8 │
└────────────┴──────────┴──────────┴─────────────┘

An Enum fixes the categories and their order up front, so a sort or a group follows low, mid, high instead of the alphabet. Casting a value that is not in the list raises an error. A pl.Categorical column sorts alphabetically in Polars 2.1.

expr_level = pl.Enum(["low", "mid", "high"])
binned = genes.with_columns(
expr_bin=pl.when(pl.col("basemean") <= 1000).then(pl.lit("low"))
.when(pl.col("basemean") <= 3000).then(pl.lit("mid"))
.otherwise(pl.lit("high"))
.cast(expr_level)
)
print(binned.group_by("expr_bin").agg(n=pl.len()).sort("expr_bin"))
shape: (3, 2)
┌──────────┬─────┐
│ expr_bin ┆ n │
│ --- ┆ --- │
│ enum ┆ u32 │
╞══════════╪═════╡
│ low ┆ 4 │
│ mid ┆ 7 │
│ high ┆ 9 │
└──────────┴─────┘

strip_prefix turns UCSC chromosome names into Ensembl names.

print(genes.select(
pl.col("symbol"),
pl.col("chromosome").str.strip_prefix("chr").alias("chrom"),
pl.col("symbol").str.to_lowercase().alias("lower"),
).head(3))
shape: (3, 3)
┌────────┬───────┬───────┐
│ symbol ┆ chrom ┆ lower │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞════════╪═══════╪═══════╡
│ TP53 ┆ 17 ┆ tp53 │
│ BRCA1 ┆ 17 ┆ brca1 │
│ EGFR ┆ 7 ┆ egfr │
└────────┴───────┴───────┘

extract_groups returns a struct with one field per named group. unnest spreads the fields into columns, and the parts start as text.

loci = pl.DataFrame({
"locus": ["chr17:7661779-7687538", "chr7:55019017-55211628"],
})
pattern = r"(?<chrom>\w+):(?<start>\d+)-(?<end>\d+)"
parts = (
loci.select(pl.col("locus").str.extract_groups(pattern))
.unnest("locus")
.with_columns(pl.col("start", "end").cast(pl.Int64))
.with_columns(width=pl.col("end") - pl.col("start"))
)
print(parts)
shape: (2, 4)
┌───────┬──────────┬──────────┬────────┐
│ chrom ┆ start ┆ end ┆ width │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═══════╪══════════╪══════════╪════════╡
│ chr17 ┆ 7661779 ┆ 7687538 ┆ 25759 │
│ chr7 ┆ 55019017 ┆ 55211628 ┆ 192611 │
└───────┴──────────┴──────────┴────────┘

str.split turns a delimited column into a list column, and explode gives each list item its own row.

go = pl.DataFrame({
"symbol": ["TP53", "BRCA1", "EGFR"],
"go_terms": ["GO:0006915;GO:0006974", "GO:0006281;GO:0006974",
"GO:0007169"],
})
go_long = go.with_columns(go_term=pl.col("go_terms").str.split(";")).explode(
"go_term"
)
print(go_long.select("symbol", "go_term"))
shape: (5, 2)
┌────────┬────────────┐
│ symbol ┆ go_term │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪════════════╡
│ TP53 ┆ GO:0006915 │
│ TP53 ┆ GO:0006974 │
│ BRCA1 ┆ GO:0006281 │
│ BRCA1 ┆ GO:0006974 │
│ EGFR ┆ GO:0007169 │
└────────┴────────────┘
renamed = genes.rename({"symbol": "gene", "log2fc": "lfc"})
print(renamed.select("gene", "lfc").head(3))
shape: (3, 2)
┌───────┬───────┐
│ gene ┆ lfc │
│ --- ┆ --- │
│ str ┆ f64 │
╞═══════╪═══════╡
│ TP53 ┆ 0.61 │
│ BRCA1 ┆ -2.08 │
│ EGFR ┆ 1.5 │
└───────┴───────┘

Polars does not promise the row order after a join. maintain_order="left" keeps the order of the left table.

pathways = pl.DataFrame({
"symbol": ["TP53", "BRCA1", "EGFR", "KRAS", "PTEN", "ATM"],
"pathway": ["p53 signaling", "DNA repair", "EGFR signaling",
"MAPK signaling", "PI3K signaling", "DNA repair"],
})
left = genes.select("symbol", "log2fc").join(
pathways, on="symbol", how="left", maintain_order="left"
)
print(left.head(5))
shape: (5, 3)
┌────────┬────────┬────────────────┐
│ symbol ┆ log2fc ┆ pathway │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ str │
╞════════╪════════╪════════════════╡
│ TP53 ┆ 0.61 ┆ p53 signaling │
│ BRCA1 ┆ -2.08 ┆ DNA repair │
│ EGFR ┆ 1.5 ┆ EGFR signaling │
│ MYC ┆ 1.88 ┆ null │
│ KRAS ┆ -3.9 ┆ MAPK signaling │
└────────┴────────┴────────────────┘

A semi join keeps the genes that have a pathway. An anti join keeps the ones that do not.

with_pathway = genes.join(pathways, on="symbol", how="semi")
no_pathway = genes.join(pathways, on="symbol", how="anti")
print(sorted(with_pathway["symbol"].to_list()))
print(no_pathway.height)
['BRCA1', 'EGFR', 'KRAS', 'PTEN', 'TP53']
15

A full join keeps both sides. coalesce=True merges the two key columns into one, so the ATM row from the pathway table keeps its symbol.

full = genes.select("symbol", "log2fc").join(
pathways, on="symbol", how="full", coalesce=True
)
print(full.filter(pl.col("log2fc").is_null()))
shape: (1, 3)
┌────────┬────────┬────────────┐
│ symbol ┆ log2fc ┆ pathway │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ str │
╞════════╪════════╪════════════╡
│ ATM ┆ null ┆ DNA repair │
└────────┴────────┴────────────┘

how="diagonal" stacks frames with different columns and fills the gaps with null.

run_one = genes.head(2).select("symbol", "log2fc")
run_two = genes.slice(2, 2).select("symbol", "log2fc", "pvalue")
print(pl.concat([run_one, run_two], how="diagonal"))
shape: (4, 3)
┌────────┬────────┬────────┐
│ symbol ┆ log2fc ┆ pvalue │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪════════╪════════╡
│ TP53 ┆ 0.61 ┆ null │
│ BRCA1 ┆ -2.08 ┆ null │
│ EGFR ┆ 1.5 ┆ 0.1941 │
│ MYC ┆ 1.88 ┆ 0.1786 │
└────────┴────────┴────────┘

A microarray often has several probes for one gene. is_duplicated() is true for every copy of a repeated value.

probes = pl.DataFrame({
"symbol": ["TP53", "MYC", "MYC", "EGFR", "EGFR"],
"probe": ["p1", "p2", "p3", "p4", "p5"],
"basemean": [2213.9, 1596.2, 310.5, 3516.3, 4022.0],
})
print(probes.filter(pl.col("symbol").is_duplicated()))
shape: (4, 3)
┌────────┬───────┬──────────┐
│ symbol ┆ probe ┆ basemean │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞════════╪═══════╪══════════╡
│ MYC ┆ p2 ┆ 1596.2 │
│ MYC ┆ p3 ┆ 310.5 │
│ EGFR ┆ p4 ┆ 3516.3 │
│ EGFR ┆ p5 ┆ 4022.0 │
└────────┴───────┴──────────┘

Sort so the row you want comes first, then unique(keep="first") keeps it. Without maintain_order=True the surviving rows come back in no fixed order. keep="none" drops every gene that has a repeat.

best = probes.sort("basemean", descending=True).unique(
subset="symbol", keep="first", maintain_order=True
)
print(best)
print(probes.unique(subset="symbol", keep="none")["symbol"].to_list())
shape: (3, 3)
┌────────┬───────┬──────────┐
│ symbol ┆ probe ┆ basemean │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞════════╪═══════╪══════════╡
│ EGFR ┆ p5 ┆ 4022.0 │
│ TP53 ┆ p1 ┆ 2213.9 │
│ MYC ┆ p2 ┆ 1596.2 │
└────────┴───────┴──────────┘
['TP53']

unpivot replaced melt. With no on=, it stacks every column that is not in index.

expr_wide = pl.DataFrame({
"symbol": ["TP53", "BRCA1", "EGFR"],
"ctrl_1": [10.2, 8.5, 12.1],
"ctrl_2": [10.6, 8.1, 11.8],
"trt_1": [15.3, 6.2, 18.4],
"trt_2": [14.9, 6.6, 17.9],
})
expr_long = expr_wide.unpivot(
index="symbol", variable_name="sample", value_name="expression"
).with_columns(condition=pl.col("sample").str.split("_").list.first())
print(expr_long.head(4))
shape: (4, 4)
┌────────┬────────┬────────────┬───────────┐
│ symbol ┆ sample ┆ expression ┆ condition │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ str │
╞════════╪════════╪════════════╪═══════════╡
│ TP53 ┆ ctrl_1 ┆ 10.2 ┆ ctrl │
│ BRCA1 ┆ ctrl_1 ┆ 8.5 ┆ ctrl │
│ EGFR ┆ ctrl_1 ┆ 12.1 ┆ ctrl │
│ TP53 ┆ ctrl_2 ┆ 10.6 ┆ ctrl │
└────────┴────────┴────────────┴───────────┘
print(expr_long.pivot(on="sample", index="symbol", values="expression"))
shape: (3, 5)
┌────────┬────────┬────────┬───────┬───────┐
│ symbol ┆ ctrl_1 ┆ ctrl_2 ┆ trt_1 ┆ trt_2 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════╪════════╪════════╪═══════╪═══════╡
│ TP53 ┆ 10.2 ┆ 10.6 ┆ 15.3 ┆ 14.9 │
│ BRCA1 ┆ 8.5 ┆ 8.1 ┆ 6.2 ┆ 6.6 │
│ EGFR ┆ 12.1 ┆ 11.8 ┆ 18.4 ┆ 17.9 │
└────────┴────────┴────────┴───────┴───────┘

aggregate_function handles repeated keys, here the two replicates per condition.

per_condition = expr_long.pivot(
on="condition", index="symbol", values="expression",
aggregate_function="mean",
)
print(per_condition)
shape: (3, 3)
┌────────┬───────┬───────┐
│ symbol ┆ ctrl ┆ trt │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪═══════╪═══════╡
│ TP53 ┆ 10.4 ┆ 15.1 │
│ BRCA1 ┆ 8.3 ┆ 6.4 │
│ EGFR ┆ 11.95 ┆ 18.15 │
└────────┴───────┴───────┘

A when with no otherwise gives null wherever the condition fails, here where the mean count is under 500.

masked = genes.with_columns(
log2fc=pl.when(pl.col("basemean") >= 500).then(pl.col("log2fc"))
)
print(masked["log2fc"].null_count())
print(masked.drop_nulls("log2fc").height)
print(masked["log2fc"].fill_null(0).null_count())
1
19
0

Polars keeps null and NaN apart. A NaN from NumPy, or from zero divided by zero in a Polars column, is a float value, so fill_null leaves it alone.

vals = pl.Series("x", [1.0, float("nan"), None])
print(vals.null_count(), vals.is_nan().sum())
print(vals.fill_null(0).to_list())
print(vals.fill_nan(None).to_list())
1 1
[1.0, nan, 0.0]
[1.0, None, None]
from pathlib import Path
out_dir = Path("outputs")
out_dir.mkdir(exist_ok=True)
table = genes.select(
"symbol", "chromosome", "role", "log2fc", "pvalue", "basemean"
)
table.write_csv(out_dir / "genes.csv")
table.write_csv(out_dir / "genes.tsv", separator="\t")
table.write_parquet(out_dir / "genes.parquet")
print(pl.read_csv(out_dir / "genes.tsv", separator="\t").shape)
(20, 6)

scan_csv reads nothing yet. It returns a LazyFrame, and each call adds a step to a plan.

query = (
pl.scan_csv(out_dir / "genes.csv")
.filter(pl.col("basemean") > 1000)
.group_by("role")
.agg(n=pl.len(), mean_log2fc=pl.col("log2fc").mean().round(2))
.sort("role")
)
print(query.explain())
SORT BY [col("role")]
AGGREGATE[maintain_order: false]
[len().alias("n"), col("log2fc").mean().round().alias("mean_log2fc")] BY [col("role")]
FROM
simple π 2/2 ["role", "log2fc"]
Csv SCAN [outputs/genes.csv]
PROJECT 3/6 COLUMNS
SELECTION: col("basemean") > 1000.0
ESTIMATED ROWS: 20

Read the plan from the bottom up. The scan reads only the three columns the query uses, PROJECT 3/6 COLUMNS, and applies the filter as it reads. collect() runs the plan.

print(query.collect())
shape: (2, 3)
┌────────────┬─────┬─────────────┐
│ role ┆ n ┆ mean_log2fc │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 │
╞════════════╪═════╪═════════════╡
│ oncogene ┆ 9 ┆ -0.11 │
│ suppressor ┆ 7 ┆ -0.26 │
└────────────┴─────┴─────────────┘

scan_parquet works the same way. engine="streaming" processes the file in batches, and it replaces collect(streaming=True), which Polars 2.0 removed.

sig_lazy = (
pl.scan_parquet(out_dir / "genes.parquet")
.filter(pl.col("pvalue") < 0.05)
.select("symbol", "log2fc", "pvalue")
.sort("pvalue")
)
print(sig_lazy.collect(engine="streaming"))
shape: (6, 3)
┌────────┬────────┬────────┐
│ symbol ┆ log2fc ┆ pvalue │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪════════╪════════╡
│ RB1 ┆ -0.63 ┆ 0.0089 │
│ ALK ┆ 0.74 ┆ 0.0261 │
│ APC ┆ -0.03 ┆ 0.0309 │
│ SMAD4 ┆ -1.72 ┆ 0.038 │
│ PIK3CA ┆ -2.6 ┆ 0.039 │
│ KIT ┆ 1.76 ┆ 0.0455 │
└────────┴────────┴────────┘

sink_parquet writes a lazy result to disk without building the full table in memory.

sig_lazy.sink_parquet(out_dir / "significant.parquet")
print(pl.read_parquet(out_dir / "significant.parquet").height)
6
genes_pd = genes.select("symbol", "log2fc").to_pandas()
print(genes_pd.dtypes)
print(genes.select("log2fc", "pvalue").to_numpy()[:2])
print(pl.from_pandas(genes_pd).schema)
symbol str
log2fc float64
dtype: object
[[ 0.61 0.1516]
[-2.08 0.071 ]]
Schema({'symbol': String, 'log2fc': Float64})

Each call in the left column raises an error under Polars 2.1.

Old call Use now
df.groupby("g") df.group_by("g")
df.melt(id_vars=, value_vars=) df.unpivot(index=, on=)
df.pivot(columns="c", ...) df.pivot(on="c", ...)
df.with_row_count() df.with_row_index()
pl.count() pl.len()
pl.col("x").apply(f) pl.col("x").map_elements(f, return_dtype=...)
pl.col("x").map_dict(mapping) pl.col("x").replace(mapping)
pl.col("x").cumsum() pl.col("x").cum_sum()
pl.col("s").str.lengths() pl.col("s").str.len_chars()
df.join(other, how="outer") df.join(other, how="full")
lf.collect(streaming=True) lf.collect(engine="streaming")
  • Polars Essentials introduces expressions, group_by, and lazy mode one step at a time.
  • Data Wrangling works through each operation on a long RNA-seq counts table, with dplyr and Polars side by side. Its Window & Rank, Joins, and Reshaping pages go further than this sheet.
  • The pandas cheatsheet runs the same gene table.

The Polars project gives its Zenodo software record as the citation for the library.

  • Polars expressions and contexts

    The guide explains how select, with_columns, filter, and group_by evaluate expressions. Its examples distinguish a column expression from the context that applies it to a table.