agg with Several Summaries

More than one answer per group, named as you want them.

A list of functions

agg takes several summaries at once and gives you a column for each.

import pandas as pd

df = pd.DataFrame({"k": ["a", "a", "b"], "v": [1, 3, 5]})
out = df.groupby("k")["v"].agg(["min", "max", "mean"])
print(out.loc["a"].tolist())

Naming the outputs

Named aggregation says what each column means, which matters when the reader is not you.

import pandas as pd

df = pd.DataFrame({"k": ["a", "a"], "v": [1, 3]})
out = df.groupby("k").agg(lowest=("v", "min"), highest=("v", "max"))
print(list(out.columns))

Exercise

Try It Yourself

Write range_by(df) returning a dictionary of each key to the difference between its highest and lowest v.

Press Run to see output

Check Your Understanding