Complete worked example
python
import pandas as pd
def inspect_example(rows):
frame = pd.DataFrame(rows, columns=["id", "metric", "value"]).astype({"id": "string", "metric": "string", "value": "Float64"})
if frame[["id", "metric"]].isna().any().any() or (~frame["metric"].isin(["views", "applications"])).any() or frame.duplicated(["id", "metric"]).any():
raise ValueError("ambiguous measurement cell")
metrics = ["views", "applications"]
wide = frame.pivot(index="id", columns="metric", values="value").reindex(columns=metrics)
wide = wide.astype("Float64").rename_axis(columns=None).reset_index()
return wide.sort_values("id").reset_index(drop=True)- Reasoning
- Create typed id, metric and value columns. Reject missing identity fields, unsupported metric names and duplicate ID-metric pairs. Pivot id into the row index and metric into columns, then reindex the two declared output columns so a batch containing only one metric still has a stable schema. Rename the column-axis metadata, reset ID into an ordinary column and sort IDs for deterministic output. Trace role a with views ten and applications two, plus role b with only views five. The wide table contains a complete a row and a missing applications cell for b. Reordering the long observations must not change those associations.