Aggregating several ways at once in Python
agg names the outputs, so the result needs no renaming afterwards.
import pandas as pd
frame = pd.DataFrame({
"lang": ["python", "python", "rust", "rust"],
"tpm": [104, 91, 98, 88],
"errors": [1, 4, 0, 2],
})
summary = frame.groupby("lang").agg(
runs=("tpm", "size"),
best=("tpm", "max"),
average=("tpm", "mean"),
clean=("errors", lambda s: (s == 0).sum()),
)
print(summary.round(1))
print(frame.groupby("lang")["tpm"].agg(["min", "max"]))
How it works
- Named aggregation pairs an output name with a column and a function.
- A list of functions gives a column per function.
- A custom lambda works anywhere a name does.
Keywords and builtins used here
aslambdaprint
The run, in numbers
- Lines
- 16
- Characters to type
- 374
- Tokens
- 172
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 94 seconds.
Step 2 of 5 in Grouping, step 15 of 26 in pandas.