Putting a Join to Work

Two files, one question, and the checks that keep the answer honest.

The shape of a real answer

Load both, check what came in, join on the key, check the row count survived, then summarise. The checks are the part people skip.

import pandas as pd

people = pd.read_csv("people.csv")
scores = pd.read_csv("scores.csv")
out = pd.merge(people, scores, on="id", how="left")
print(len(people), len(out))

Summarise last

Once the join is trusted, the summary is one line. Doing it before you have checked the join is how a confident wrong number gets published.

import pandas as pd

df = pd.DataFrame({"team": ["a", "a", "b"], "score": [90, 80, 70]})
print(df.groupby("team")["score"].mean().round(1).to_dict())

Exercise

Try It Yourself

Two files are supplied: people.csv with id and team, and scores.csv with id and score. Write team_means(people_path, scores_path) returning a dictionary of team to mean score, rounded to one decimal place.

Press Run to see output

Check Your Understanding