Pirate Cheat Sheets
Fast DataFrames with a lazy query engine

Polars
cheat sheet

Polars at a glance: read and write files, select and filter with expressions, group by, joins, reshaping, strings and dates, window functions, the lazy API, SQL and the pandas mapping.

Version
v2.1.0
Snippets
125
Sections
12

Version notes · Polars 2.1.0

  • 2.0: LazyFrame.collect() uses the streaming engine by default. Row order is no longer incidental: sort explicitly, or pass maintain_order=.
  • 2.0: queries spill to disk (out-of-core) above 80 % of RAM. read_csv now runs as scan_csv(…).collect().
  • 2.0 deprecates cut() / qcut() in favour of bin_intervals() / bin_quantiles() (left-closed, labels= required).
  • 2.0 removed LazyFrame.profile() and the DataFrame interchange protocol; join(how="outer") is now how="full".

A DataFrame library written in Rust on Apache Arrow. You describe columns with expressions (pl.col(…)); Polars runs them in parallel, and the lazy API optimizes the whole query first.

ReadsCSVParquetJSON / NDJSONExcelIPC / ArrowDeltaIcebergdatabasesS3 / GCS

Multi-core

every query runs in parallel

Lazy & optimized

predicate + projection pushdown

Bigger than RAM

streaming engine, spills to disk

No index

just columns, no .loc / .iloc

Quick start

import polars as pldf = pl.read_csv("sales.csv", try_parse_dates=True)out = (    df.filter(pl.col("amount") > 0)      .group_by("region")      .agg(pl.col("amount").sum().alias("total"), pl.len())      .sort("total", descending=True))print(out)

Read

  • Import (uv add polars)
  • CSV (separator=";", try_parse_dates=True)
  • Force column types
  • Parquet
  • JSON Lines (read_json for an array)
  • Excel (needs fastexcel)
  • SQL database (connectorx / ADBC)
  • Cloud storage + globs

Write & convert

  • Parquet (zstd by default)
  • CSV
  • JSON Lines
  • Excel (needs xlsxwriter)
  • From a dict
  • From a list of dicts
  • From pandas (df.to_pandas() back)
  • To a list of dicts
  • (rows, columns)
  • Column names → dtypes
  • First rows (tail, sample(5))
  • One line per column
  • Summary statistics
  • Nulls per column
  • Frequencies
  • Distinct values
  • Memory used
  • Print more rows
  • Pick columns
  • Computed column
  • Add / replace a column
  • Same, keyword style
  • Constant column
  • All columns of a type
  • Selectors
  • By type / name pattern
  • Remove columns
  • Rename
  • Change type

Expressions inside one select / with_columns run in parallel. Chain a second with_columns to use a column you just created.

  • Keep matching rows
  • And (| or, ~ not)
  • Several conditions = and
  • In a list
  • Nulls (is_not_null)
  • Range, inclusive
  • Sort
  • Several keys
  • Drop duplicates
  • Largest 5 rows
  • Rows 100–149
  • Rows per group
  • Several aggregations
  • Several keys
  • Groups in first-seen order
  • Conditional aggregation
  • List of values per group
  • Percentile (median, std, n_unique…)
  • Time buckets (sorted ts)
  • Aggregate the whole frame

Group order is not stable: add .sort(…) or maintain_order=True when the order matters.

Conditions & nulls

  • If / else
  • Chained cases
  • Replace nulls (strategy="forward")
  • NaN → null
  • First non-null
  • Drop rows with nulls

Window & row-wise

  • Group total on every row
  • Rank within group
  • Previous value per group
  • Running total
  • Moving average
  • Across columns
  • Bucket values (2.0+, replaces cut)

Strings

  • Case (to_uppercase, to_titlecase)
  • Trim whitespace
  • Substring (regex by default)
  • Regex replace
  • Regex group
  • To a list
  • Length

Dates & lists

  • Parse a date
  • Parse a timestamp
  • Parts (month, weekday, hour…)
  • Start of the month
  • Time zones
  • Date sequence
  • List length (list.contains, list.first)
  • One row per list item
  • Inner join
  • left · right · full · semi · anti · cross
  • Different key names
  • Keep the left row order
  • Fail on duplicate keys
  • Nearest earlier match (sorted keys)
  • Stack rows (same columns)
  • Stack, fill missing columns with null
  • Side by side
  • Long → wide
  • Wide → long (was melt)
  • Rows ↔ columns
  • Split into one frame per group
  • Add a 0-based row number
  • Struct column → columns
  • Lazy scan: nothing is read yet
  • Also scan_ndjson, scan_ipc, scan_delta
  • Make any DataFrame lazy
  • Optimize, then run (streaming)
  • Use the in-memory engine instead
  • Stream the result to disk
  • Print the optimized plan
  • Output columns without running
  • Run on a sample
  • Run without blocking asyncio

Scans push filters and column selection down into the file reader, so a lazy query on Parquet reads only the row groups and columns it needs.

  • Query one frame (self)
  • Frames in scope by variable name
  • Explicit registry
  • Run a query
pandasPolars
  • df["a"] # or pl.col("a") in expressions
  • df.filter(pl.col("a") > 1)
  • df.with_columns(c=pl.col("a") * 2)
  • df.group_by("k").agg(pl.col("a").sum())
  • df.sort("a")
  • df.join(o, on="id", how="left")
  • df.unpivot(index="k")
  • df.unique()
  • df.fill_null(0)
  • df.head(5)
  • df.select(pl.struct("a", "b").map_elements(f)) # slow: prefer expressions