Polars 2 cheatsheet

Polars 2: Expressions, grouping and joins

8 common Polars 2 tasks.

Group and aggregate

Compute several aggregates per group.

df.group_by("team").agg(
    pl.len().alias("people"),
    pl.col("age").mean().alias("avg_age"),
)

Conditional columns

Set a value by condition, like CASE WHEN in SQL.

df.with_columns(
    pl.when(pl.col("age") >= 40).then(pl.lit("senior")).otherwise(pl.lit("junior")).alias("level")
)

Join two DataFrames

Combine DataFrames on a key. how can be inner, left, full, semi or anti.

teams = pl.DataFrame({"team": ["a", "b"], "city": ["Rome", "Oslo"]})
df.join(teams, on="team", how="left")

Handle missing values

Replace nulls, or drop rows that contain them.

df.with_columns(pl.col("age").fill_null(0))
df.drop_nulls()

Work with strings

Use the str namespace for text operations.

df.filter(pl.col("name").str.contains("a"))
df.with_columns(pl.col("name").str.len_chars().alias("length"))

Work with dates

Parse text to dates and extract parts with the dt namespace.

dates = pl.DataFrame({"d": ["2026-01-15", "2026-03-02"]}).with_columns(pl.col("d").str.to_date())
dates.with_columns(pl.col("d").dt.month().alias("month"))

Window functions

Compute a value per group while keeping every row.

df.with_columns(pl.col("age").mean().over("team").alias("team_avg_age"))

Pivot a DataFrame

Turn values of one column into columns.

long = pl.DataFrame({"team": ["a", "a", "b"], "kind": ["x", "y", "x"], "n": [1, 2, 3]})
long.pivot(on="kind", index="team", values="n")

Was this page helpful?