Complete worked example
python
import pandas as pd
def inspect_example(rows):
frame = pd.DataFrame(rows, columns=["id", "country", "score"]).astype({"id": "string", "country": "string", "score": "Float64"})
if frame["id"].isna().any() or frame["id"].duplicated().any():
raise ValueError("unique role IDs required")
frame["country_mean"] = frame.groupby("country", dropna=False)["score"].transform("mean")
frame["deviation"] = frame["score"] - frame["country_mean"]
return frame[["id", "score", "country_mean", "deviation"]]- Reasoning
- Build the typed role frame and reject missing or duplicated IDs. Group by country with an explicit missing-key policy, select score and call transform("mean"). The returned Series has one value for each input row and aligns with the frame index. Subtract that context from score to obtain deviation. Return the selected columns in original row order. For UA scores two and four, both rows receive mean three and deviations negative one and positive one. An IL score of ten receives mean ten and deviation zero. The IL value must not influence either UA deviation. A missing UA score receives context three but retains a missing deviation.