typestar

Window expressions in Python

over computes per group but keeps every row, which agg does not.

import polars as pl

frame = pl.DataFrame({
    "lang": ["python", "python", "rust", "rust"],
    "tpm": [104, 91, 98, 88],
})

ranked = frame.with_columns(
    pl.col("tpm").mean().over("lang").alias("group_mean"),
    (pl.col("tpm") / pl.col("tpm").sum().over("lang")).round(3).alias("share"),
    pl.col("tpm").rank(descending=True).over("lang").alias("rank_in_group"),
)
print(ranked)

How it works

  1. expr.over(key) broadcasts the group's value back to its rows.
  2. That is how you get a share of the group total.
  3. rank().over(...) numbers rows within their group.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
368
Tokens
160
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 3 of 3 in Aggregation, step 14 of 32 in Polars.

← Previous Next →