Complete worked example
python
import pandas as pd
def inspect_example(rows):
frame = pd.DataFrame(rows, columns=["country", "score"]).astype({"country": "string", "score": "Float64"})
grouped = frame.groupby("country", dropna=False, observed=True)
result = grouped.agg(roles=("score", "size"), measured=("score", "count"), mean_score=("score", "mean")).reset_index()
result = result.astype({"country": "string", "roles": "Int64", "measured": "Int64", "mean_score": "Float64"})
return result.sort_values("country", na_position="last").reset_index(drop=True)- Reasoning
- Construct nullable country and score columns, then group country with dropna=False and observed=True. Named aggregation produces roles through size, measured through count and mean_score through mean. Cast the output schema explicitly and sort country with missing values last for reproducible presentation. observed=True documents that unused categorical levels should not create phantom observed groups if the key becomes categorical later. Trace UA scores two and missing, plus one missing-country score of eight. UA has two roles, one measurement and mean two. The missing-country group has one role and one observed measurement. Those are distinct facts, not three alternative spellings of the same count.