typestar

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

  1. Named aggregation pairs an output name with a column and a function.
  2. A list of functions gives a column per function.
  3. A custom lambda works anywhere a name does.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 5 in Grouping, step 15 of 26 in pandas.

← Previous Next →