Split, Apply, Combine

The shape of every group-by, named once so the rest makes sense.

Three steps in one call

Split the rows into groups by a key, apply a summary to each group, and combine the answers into one result indexed by that key.

import pandas as pd

df = pd.DataFrame({"subject": ["maths", "art", "maths"], "score": [90, 70, 80]})
print(df.groupby("subject")["score"].mean().to_dict())

The key becomes the index

What you grouped by ends up as the index of the result, which is why the answer reads as a lookup table.

import pandas as pd

df = pd.DataFrame({"subject": ["maths", "art"], "score": [90, 70]})
out = df.groupby("subject")["score"].mean()
print(out.index.tolist())

Exercise

Try It Yourself

Write mean_by_subject(df) returning a dictionary of subject to mean score, each mean rounded to one decimal place.

Press Run to see output

Check Your Understanding