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
group_by('team')forms the groups.aggcomputes sums, means, andpl.lenper group.- The result sorts by the aggregate.
Keywords and builtins used here
as
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.
Step 1 of 3 in Aggregation, step 12 of 32 in Polars.