Aggregating several ways in Python
group_by().agg() takes a list of expressions, each named.
import polars as pl
frame = pl.DataFrame({
"lang": ["python", "python", "rust", "rust", "sql"],
"tpm": [104, 91, 98, 88, 79],
"errors": [1, 4, 0, 2, 3],
})
summary = frame.group_by("lang").agg(
pl.len().alias("runs"),
pl.col("tpm").max().alias("best"),
pl.col("tpm").mean().round(1).alias("average"),
(pl.col("errors") == 0).sum().alias("clean"),
).sort("average", descending=True)
print(summary)
How it works
- Every aggregate is an expression, so it can filter inside itself.
pl.lencounts rows in the group.- The result has one row per group and a column per expression.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 16
- Characters to type
- 399
- Tokens
- 182
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 99 seconds.
Step 2 of 3 in Aggregation, step 13 of 32 in Polars.