Complete worked example
python
from contextlib import closing
import sqlite3
import pandas as pd
def inspect_example(rows):
frame = pd.DataFrame(rows, columns=["country", "score"]).astype({"country": "string", "score": "Float64"})
types = {"country": "string", "roles": "Int64", "measured": "Int64", "mean_score": "Float64"}
report = frame.groupby("country", dropna=False).agg(roles=("score", "size"), measured=("score", "count"), mean_score=("score", "mean")).reset_index().astype(types)
with closing(sqlite3.connect(":memory:")) as connection:
frame.to_sql("observations", connection, index=False)
query = "SELECT country, COUNT(*) AS roles, COUNT(score) AS measured, AVG(score) AS mean_score FROM observations GROUP BY country"
sql_report = pd.read_sql_query(query, connection).astype(types)
report = report.sort_values("country", na_position="last").reset_index(drop=True)
sql_report = sql_report.sort_values("country", na_position="last").reset_index(drop=True)
pd.testing.assert_frame_equal(report, sql_report, check_exact=False, rtol=1e-12, atol=1e-12)
return report- Reasoning
- Build a typed country-score frame and compute roles, measured and mean_score in pandas. Use a closing context for a new sqlite3 in-memory connection, write the fixture table with index=False and run the explicit SQL aggregate. Cast both reports to the same declared schema, order country with missing values last and compare through pd.testing.assert_frame_equal. Return the pandas report only after the independent reconciliation passes. Trace UA with one score and one missing score, plus a NULL country group. Both implementations must count the UA roles as two but its observed measurements as one. Matching row counts alone would not prove the mean or coverage agrees.