typestar

Group by and aggregate in Python

Summarizing groups with aggregate expressions.

import polars as pl

df = pl.DataFrame({
    "team": ["a", "b", "a", "b", "a"],
    "player": ["kim", "sam", "rio", "noor", "tui"],
    "points": [10, 7, 12, 9, 5],
})

by_team = df.group_by("team").agg(
    pl.col("points").sum().alias("total"),
    pl.col("points").mean().alias("avg"),
    pl.len().alias("players"),
)

ranked = by_team.sort("total", descending=True)

How it works

  1. group_by('team') forms the groups.
  2. agg computes sums, means, and pl.len per group.
  3. The result sorts by the aggregate.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
346
Tokens
162
Three-star pace
110 tpm

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

Type this snippet

Step 1 of 3 in Aggregation, step 12 of 32 in Polars.

← Previous Next →