Complete worked example
python
import pandas as pd
def inspect_example(rows, companies):
if any(type(r.get("id")) is not str or not r["id"].strip() or type(r.get("company_id")) is not str or not r["company_id"].strip() or type(r.get("seq")) is not int or r["seq"] < 0 or type(r.get("technical")) is not bool for r in rows):
raise ValueError("invalid role observation")
frame = pd.DataFrame(rows, columns=["id", "company_id", "country", "technical", "updated", "seq", "score"])
frame = frame.astype({"id": "string", "company_id": "string", "country": "string", "technical": "boolean", "score": "Float64"})
dimension = pd.DataFrame(companies, columns=["company_id"]).astype("string")
if frame.duplicated(["id", "seq"]).any() or dimension["company_id"].isna().any() or dimension["company_id"].duplicated().any():
raise ValueError("ambiguous identity")
frame["country"] = frame["country"].str.strip().str.upper()
frame["updated"] = pd.to_datetime(frame["updated"], format="ISO8601", utc=True, errors="raise")
latest = frame.sort_values(["id", "updated", "seq"], kind="stable").drop_duplicates("id", keep="last")
joined = latest.merge(dimension, on="company_id", how="left", validate="many_to_one", indicator=True)
eligible = joined["_merge"].eq("both") & joined["technical"] & joined["country"].isin(["UA", "IL", "US", "CA"])
selected = joined.loc[eligible.fillna(False)]
report = selected.groupby("country").agg(roles=("id", "size"), companies=("company_id", "nunique"), measured=("score", "count"), mean_score=("score", "mean")).reset_index()
return report.astype({"country": "string", "roles": "Int64", "companies": "Int64", "measured": "Int64", "mean_score": "Float64"}).sort_values("country").reset_index(drop=True)- Reasoning
- Validate nonblank role and company IDs, nonnegative integer sequences and boolean technical flags. Require unique ID-sequence observation pairs and a unique company dimension. Parse updated timestamps as UTC, sort observations by ID, time and sequence and retain the newest per ID. Perform a validated many-to-one left lookup with an indicator, then require a matched company, a technical role and a country in UA, IL, US or CA. Aggregate only that retained population: roles counts every eligible role, measured counts known scores and mean_score averages observed scores. Include company count separately and sort countries. A role with a missing score remains a role rather than disappearing from the report.