Grouping by Several Keys

Two keys give a row per combination, and an index with two levels.

A list of columns

Grouping by subject and year gives one row per pair that actually occurs -- combinations with no rows simply are not there.

import pandas as pd

df = pd.DataFrame({"subject": ["maths", "maths"], "year": [10, 11], "score": [90, 80]})
out = df.groupby(["subject", "year"])["score"].mean()
print(out.to_dict())

Flattening the result

reset_index turns the group keys back into ordinary columns, which is usually what you want before writing the result out.

import pandas as pd

df = pd.DataFrame({"a": ["x"], "b": [1], "v": [5]})
out = df.groupby(["a", "b"])["v"].mean().reset_index()
print(list(out.columns))

Exercise

Try It Yourself

Write pairs_counted(df) returning a dictionary keyed by the (subject, year) tuple, holding how many rows each pair has.

Press Run to see output

Check Your Understanding