Data engineer comparing pandas GroupBy.first output with original event rows to verify record integrity.

Why pandas GroupBy.first Can Assemble a Record That Never Existed

Thu, Nov 26, 2026

A grouped result can preserve a plausible row_id while taking qty and state from different source rows. With the default missing-value behavior, pandas GroupBy.first is a per-column reduction: pandas 2.2.3 documents DataFrameGroupBy.first as computing the first entry of each column within a group and, by default, skipping NA values. That behavior is useful for column summaries, but it is not the same application contract as “return the first observed event record.” The skipna parameter exists explicitly in pandas 2.2.3 and is documented as having been added in 2.2.1; it is not a new 2026 capability.

The review therefore needs two independent acceptance questions. First: does the entire returned five-field tuple match the source row identified by its row_id? Second: is that source row the first event under the approved ordering rule? A tuple may fail the first test because its fields came from several records. A genuine source tuple may pass coherence but fail the second test because encounter order was wrong.

The laboratory below is deliberately narrow. It uses four nonnull string groups, unique source identifiers, explicit int64 sequence order, nullable Int64 quantities, and nullable strings. Missing payloads are preserved. F01–F10 are EXPECTED / NOT EXECUTED: only environment metadata was inspected. No GroupBy fixture was run, so no PASS transcript, timing, hash, or behavioral observation is claimed.

Define the first-event contract before selecting rows

Before reviewing code, define what one event means. In this laboratory one source event is the complete tuple:

(row_id, group, seq, qty, state)

The source row_id identifies the record; group partitions events; seq supplies the approved order; qty and state are payload fields. A missing qty or state is still part of the source event. It is not permission to borrow a later value.

For the first-event contract, the approved record is the event with the smallest admitted seq within each group. Because every (group, seq) pair in this fixture is unique, no tie policy is required. That uniqueness is a property of this bounded laboratory, not a general ordering guarantee.

This record-level declaration is the point at which a reviewer should define the row grain before cleaning. Refonte Learning’s broader cleaning workflow likewise emphasizes preserving raw input and defining what a row represents before transformations alter it.

Three policies must remain separate:

Policy

Meaning

Missing payload treatment

First event

Select the source record with the approved earliest seq

Preserve its missing values

First complete record

Select the earliest source row satisfying an explicitly approved completeness rule

Rows missing required payload fields are ineligible

First non-null per column

Reduce each column independently to an early nonmissing value

Values may legitimately come from different source rows

The third policy can be useful. The problem begins only when its result is labeled as if it were one observed event.

capture-pandas-groupby

Separate column summaries from observed events

The workflow uses six authored application decisions. They are not pandas return statuses and should not be described as library guarantees.

ACCEPT_SOURCE_ROW means the candidate is a coherent source tuple and satisfies the policy currently being reviewed. AGGREGATE_ONLY means a per-column reduction is legitimate but must be labeled as an aggregate rather than as an event. REJECT_SYNTHETIC_RECORD means the purported record cannot be reconciled to its claimed source row. HOLD_SELECTION_POLICY means the tuple exists in source but is not the approved first event. HOLD_NO_COMPLETE_RECORD applies only to the separate completeness policy when no qualifying row exists. HOLD_AMBIGUOUS_SOURCE stops processing when identity is not uniquely resolvable.

Those distinctions prevent a common review failure: using one green criterion (such as “four groups returned”) as a substitute for record identity, ordering, and policy approval.

Pin the environment and admit the source schema

This article uses the pandas 2.2.3 documentation. The environment metadata inspection reported Python 3.12.14, pandas 2.2.3, and NumPy 2.3.5 using platform and importlib.metadata. That inspection did not execute GroupBy, construct the fixture, or validate F01–F10. These versions are therefore the proposed reproduction baseline, not a claim about current latest releases.

A reviewer can recreate and inspect that environment with commands such as:

python3.12 -m venv .venv
source .venv/bin/activate

python -m pip install "pandas==2.2.3" "numpy==2.3.5"

python - <<'PY'
import platform
from importlib import metadata

print("python", platform.python_version())
print("pandas", metadata.version("pandas"))
print("numpy", metadata.version("numpy"))
PY

The authoritative literal is intentionally small enough to inspect without pandas:

ROWS = [
    ("A1", "A", 1, None, "open"),
    ("A2", "A", 2, 10, None),
    ("A3", "A", 3, 20, "closed"),
    ("B1", "B", 1, 7, "ready"),
    ("B2", "B", 2, 9, "later"),
    ("C1", "C", 1, None, None),
    ("C2", "C", 2, None, None),
    ("D1", "D", 1, None, "held"),
    ("D2", "D", 2, 4, None),
]

The admitted schema is exact:

Column

Required dtype

Admission rule

row_id

string[python]

nonmissing, nonempty, unique

group

string[python]

nonmissing

seq

int64

nonmissing; (group, seq) unique

qty

Int64

nullable; preserve NA

state

string[python]

nullable; preserve NA

A constructor and admission guard can make those assumptions executable:

import pandas as pd
from pandas.testing import assert_frame_equal
COLUMNS = ["row_id", "group", "seq", "qty", "state"]
def build_frame(rows=ROWS):
    df = pd.DataFrame(rows, columns=COLUMNS)
    return df.astype({
        "row_id": "string[python]",
        "group": "string[python]",
        "seq": "int64",
        "qty": "Int64",
        "state": "string[python]",
    })
def admit_source(df):
    if list(df.columns) != COLUMNS:
        raise ValueError("Unsupported source columns")
   expected_dtypes = {
        "row_id": "string",
        "group": "string",
        "seq": "int64",
        "qty": "Int64",
        "state": "string",
    }
    actual = {name: str(dtype) for name, dtype in df.dtypes.items()}
    if actual != expected_dtypes:
        raise ValueError(f"Unsupported dtypes: {actual}")
    if df["row_id"].isna().any() or (df["row_id"].str.len() == 0).any():
        raise ValueError("row_id must be nonmissing and nonempty")
    if not df["row_id"].is_unique:
        raise ValueError("row_id must be unique")
    if df["group"].isna().any() or df["seq"].isna().any():
        raise ValueError("group and seq must be nonmissing")
    if df.duplicated(["group", "seq"]).any():
        raise ValueError("Unresolved sequence tie")

Each case should build a fresh frame, retain raw_snapshot = df.copy(deep=True), perform its candidate operation, and then verify source preservation with assert_frame_equal(raw_snapshot, df, check_exact=True, check_dtype=True). pandas documents assert_frame_equal as a DataFrame equality assertion; check_exact=True requests exact numeric comparison and dtype checking is enabled by check_dtype=True. Snapshot equality is useful evidence, but it is supplementary: it cannot tell us whether the selector chose the right record.

Keep grouping-key policies outside this experiment

Every admitted group key is a nonnull string. Consequently, this article does not repeat missing-key GroupBy reconciliation, whose separate question is which records enter grouped output.

The baseline grouping expression is:

def grouped(df, *, sort=False):
    return df.groupby(
        "group",
        sort=sort,
        dropna=False,
        observed=True,
    )

dropna=False is explicit but has no missing group keys to recover in this fixture. observed=True concerns categorical groupers; the pandas DataFrame.groupby API documents observed as applying when groupers are categorical, so there is no categorical-expansion issue to investigate here. pandas also documents that sort controls group-key sorting but does not change observation order within each group, and that the argument has no effect on filtrations such as head and nth.

Write the independent source-row manifest

The first-event oracle must exist before any selector runs. Do not manufacture it from first, nth, head, a groupby().min(), or candidate agreement. For this literal, the authored manifest is:

Group

Approved first ID

Complete expected tuple

A

A1

("A1","A",1,null,"open")

B

B1

("B1","B",1,7,"ready")

C

C1

("C1","C",1,null,null)

D

D1

("D1","D",1,null,"held")

The separate first-complete-record oracle, requiring both qty and state, is:

Group

First complete ID

Policy state

A

A3

qualifying source row

B

B1

qualifying source row

C

None

HOLD_NO_COMPLETE_RECORD

D

None

HOLD_NO_COMPLETE_RECORD

Encode those expectations directly:

FIRST_EVENT = {
    "A": ("A1", "A", 1, None, "open"),
    "B": ("B1", "B", 1, 7, "ready"),
    "C": ("C1", "C", 1, None, None),
    "D": ("D1", "D", 1, None, "held"),
}

FIRST_COMPLETE = {
    "A": ("A3", "A", 3, 20, "closed"),
    "B": ("B1", "B", 1, 7, "ready"),
}

NO_COMPLETE = {
    "C": "HOLD_NO_COMPLETE_RECORD",
    "D": "HOLD_NO_COMPLETE_RECORD",
}

These constants are authored expected outcomes. They are not observations.

Compare every field with the claimed raw record

Identity reconciliation starts with unique row_id, because a dictionary lookup silently overwrites duplicates. Check uniqueness first, then construct the lookup:

def raw_lookup(df):
    if not df["row_id"].is_unique:
        raise ValueError("HOLD_AMBIGUOUS_SOURCE")
    return {
        str(row.row_id): row
        for row in df.itertuples(index=False)
    }

Nullable values require deliberate normalization. pandas’ missing-data guide explains that pd.NA propagates through equality (pd.NA == 1 and even pd.NA == pd.NA produce an unknown value) and recommends isna() for detecting missingness. Nullable integer storage also uses pd.NA.

Therefore normalize scalars before ordinary Python tuple comparison:

def norm_scalar(value):
    if pd.isna(value):
        return None
    if isinstance(value, str):
        return value
    if hasattr(value, "item"):
        return value.item()
    return value
def norm_tuple(values):
    return tuple(norm_scalar(v) for v in values)
def candidate_rows(df):
    if list(df.columns) != COLUMNS:
        raise ValueError(f"Unexpected candidate columns: {list(df.columns)}")
    return [norm_tuple(row) for row in df.itertuples(index=False, name=None)]
def reconcile_candidate(candidate, raw, first_manifest=FIRST_EVENT):
    lookup = raw_lookup(raw)
    findings = []
    for tup in candidate_rows(candidate):
        row_id, group, seq, qty, state = tup
        source = lookup.get(row_id)
        if source is None:
            findings.append({
                "row_id": row_id,
                "coherent": False,
                "first_event": False,
                "reason": "row_id absent from source",
            })
            continue
        source_tuple = norm_tuple((
            source.row_id,
            source.group,
            source.seq,
            source.qty,
            source.state,
        ))
        coherent = tup == source_tuple

        expected = first_manifest.get(group)
        expected_id = None if expected is None else expected[0]
        first_event = coherent and row_id == expected_id

        findings.append({
            "row_id": row_id,
            "coherent": coherent,
            "first_event": first_event,
            "candidate": tup,
            "source": source_tuple,
            "expected_first_id": expected_id,
        })
    return findings

The first Boolean answers source-record integrity. The second answers selection policy. They must not be collapsed into one test.

Use a complete group as a positive control

F01 limits input to B1 and B2, already in approved sequence order, and applies:

candidate = (
    grouped(df)
    .first(numeric_only=False, min_count=-1, skipna=True)
)

pandas 2.2.3 documents first as a column-wise operation, with skipna=True the default, numeric_only=False available explicitly, and min_count=-1 as the default valid-value threshold.

For B, the first row is complete: B1, B, 1, 7, ready. No field needs a later nonmissing donor. The expected normalized result is therefore the intact B1 tuple, and F01’s authored decision is ACCEPT_SOURCE_ROW.

That control matters. The issue is not “GroupBy.first always fabricates rows.” When the first entries of all reduced fields originate from the same source event, its values can coincide with a real row. The review question is whether that coincidence holds for the data and contract being approved.

Trace the columns that create a synthetic record

F02 applies the same default-style aggregation to all nine records. The expected group identifiers remain plausible:

A1, B1, C1, D1

But those identifiers do not establish tuple provenance.

For group A, the source begins:

row_id

seq

qty

state

A1

1

null

open

A2

2

10

null

A3

3

20

closed

Because first(skipna=True) reduces columns independently and skips NA values, A’s expected reduced fields are row_id=A1, seq=1, qty=10, and state=open. That produces:

("A1","A",1,10,"open")

No A source row has that tuple. A1 has qty=null; A2 has state=null; A3 has qty=20 and state=closed.

D has the same failure shape:

("D1","D",1,4,"held")

D1 supplies the identity, sequence, and state, while D2 supplies quantity 4.

B remains intact because B1 is complete. C also reconciles to C1: its payload columns are all missing throughout the group, so their reductions remain missing rather than acquiring invented nonmissing donors.

Expected F02 classification:

Group

Claimed ID

Tuple coherent?

First-event ID correct?

Decision

A

A1

No

ID only

REJECT_SYNTHETIC_RECORD

B

B1

Yes

Yes

ACCEPT_SOURCE_ROW

C

C1

Yes

Yes

ACCEPT_SOURCE_ROW

D

D1

No

ID only

REJECT_SYNTHETIC_RECORD

The overall report cannot be accepted as “first source event per group” merely because its group count is four and its IDs look reasonable. The payload must reconcile too.

Record the nonmissing donor for each reduced field

A donor ledger explains why the aggregation is legitimate as a column reduction while invalid as an observed-record claim.

For F02 the expected donor ledger is:

Group

row_id donor

seq donor

qty donor

state donor

A

A1

A1

A2

A1

B

B1

B1

B1

B1

C

C1

C1

none

none

D

D1

D1

D2

D1

Do not fabricate a donor for C’s missing payload reductions. “No nonmissing donor” is different from “C1 donated an NA.” Group membership and reduced-field donation are separate concepts.

A donor ledger can be reconstructed from the retained source without using candidate values:

REDUCED_FIELDS = ["row_id", "seq", "qty", "state"]
def first_nonmissing_donor_ledger(df):
    rows = []
    for group_value, part in grouped(df):
        for field in REDUCED_FIELDS:
            donor_id = None
            donor_value = None
            for row in part.itertuples(index=False):
                value = getattr(row, field)
                if not pd.isna(value):
                    donor_id = str(row.row_id)
                    donor_value = norm_scalar(value)
                    break
            rows.append({
                "group": str(group_value),
                "field": field,
                "donor_row_id": donor_id,
                "donor_value": donor_value,
            })
    return pd.DataFrame(rows)

This is conceptually adjacent to Power Query donor-boundary validation, but the operation is different. That article checks values propagated into multiple retained rows and prevents cross-customer donation; here we audit a within-group reduction that emits one summary row.

If the business actually wants “first non-null value of each field,” keep the result and label it accordingly: AGGREGATE_ONLY. Do not rename it “first event.”

Compare aggregation and source-row selectors

F03 changes one documented parameter:

candidate_first_no_skip = (
    grouped(df)
    .first(numeric_only=False, min_count=-1, skipna=False)
)

With skipna=False, the expected reduced value for each field comes from the first position, including missing values. On this admitted fixture, normalized F03 tuples should therefore match A1, B1, C1, and D1 exactly. That makes F03 ACCEPT_SOURCE_ROW for this bounded contract. The important qualification is that first remains an aggregation API; this case demonstrates expected value agreement under these inputs, not a universal identity guarantee for every schema or parameter combination. The parameter itself is documented by pandas 2.2.3.

F04 uses row selection directly:

candidate_nth = grouped(df).nth(0, dropna=None)

The nth API says an integer n takes the nth row from each group; when dropna is specified, missingness filtering occurs before counting. With dropna=None, no such prefilter is requested.

F05 uses:

candidate_head = grouped(df).head(1)

GroupBy.head is documented to return a subset of original rows while preserving original index and order.

Expected F03, F04, and F05 selected identities are all A1/B1/C1/D1. The manifest remains independent; agreement among three pandas expressions is corroborating evidence, not the oracle from which expected results are derived.

Retain the raw index of each result

The raw result schemas matter.

first is an aggregation. Group keys form the result index under the baseline as_index=True, and the grouped group column is not retained as an ordinary payload column. To reconcile complete source tuples, normalize only after saving that raw schema:

def normalize_first_result(result):
    out = result.reset_index()
    return out[COLUMNS]

By contrast, nth(0, dropna=None) and head(1) are filtration-style selectors and retain source rows. In the original nine-row fixture, expected source indexes are 0, 3, 5, 7. pandas documents that GroupBy.head keeps original indexes and original order, and the GroupBy user guide treats nth as a filtration because it may return zero or multiple rows per group.

The GroupBy user guide deserves a narrow reading. Its nth subsection shows a two-column example and comments that nth(0, dropna="any") is the same as first(), but the displayed outputs have different schemas and indexes: the nth output retains the grouping column as a selected row, while first produces group-indexed aggregated output. The comment is useful for the displayed values in that restricted example; it should not be promoted into a universal multi-column whole-record equivalence.

Keep first-complete-record selection a separate policy

F06 asks a different question: what is the first event whose required payload fields are both present?

One path is:

complete_via_nth = grouped(df).nth(0, dropna="any")

The nth API documents that dropna="any" applies missingness filtering before the nth position is counted. If no qualifying nth row exists, nth does not manufacture a replacement record; its documentation demonstrates that an unavailable position can result in no row.

For an explicitly payload-scoped rule, write the policy more directly:

eligible = df.dropna(
    subset=["qty", "state"],
    how="any",
)

complete_explicit = (
    grouped(eligible)
    .nth(0, dropna=None)
)

DataFrame.dropna documents subset as the labels considered when deciding whether rows contain missing values, making the completeness fields visible in code.

In this exact five-column fixture, both paths are expected to yield A3 and B1. C and D have no row complete on both payload fields and therefore remain explicit absence states:

C -> HOLD_NO_COMPLETE_RECORD
D -> HOLD_NO_COMPLETE_RECORD

This does not repair the original first-event contract. A3 is a genuine A source row, but it is not A’s first event; it is acceptable only under the separately approved complete-record policy. B1 happens to satisfy both policies.

That separation resembles the contract discipline in pairwise and complete-case cohort auditing: completeness changes eligibility and therefore the selected population. Here, however, there is no statistical cohort question; the issue is simply which source record a row-selection policy is authorized to choose.

Validate order with a reversed-input case

F07 reverses the nine source records without altering any field:

reversed_df = build_frame(list(reversed(ROWS)))

The encounter order becomes:

D2, D1, C2, C1, B2, B1, A3, A2, A1

Applying:

candidate = grouped(reversed_df).nth(0, dropna=None)

is expected to select D2, C2, B2, and A3. Those are genuine source records. Their payloads should reconcile exactly against the raw reversed frame. Record coherence therefore passes.

The selection contract fails independently. The approved manifest still says D1, C1, B1, and A1, because approved order is seq, not input encounter order.

Now vary only group-key sorting:

candidate_sort_true = (
    reversed_df
    .groupby(
        "group",
        sort=True,
        dropna=False,
        observed=True,
    )
    .nth(0, dropna=None)
)

That is not an order repair. pandas documents that GroupBy preserves row order within each group, that sorting group keys does not sort observations inside groups, and that the sort flag does not affect filtrations such as nth or head.

Expected F07 evidence should therefore record two findings, not one:

Check

Expected finding

Source-record coherence

Pass for D2/C2/B2/A3

Approved first-event identity

Fail for all four groups

The policy decision is HOLD_SELECTION_POLICY. A valid source row is not automatically the correct source row.

Recover the approved sequence from retained rows

F08 repairs the ordering contract by sorting an owned copy on the admitted ordering fields before selecting:

ordered = reversed_df.sort_values(
    ["group", "seq"],
)

candidate = (
    grouped(ordered)
    .nth(0, dropna=None)
)

The expected candidate is A1/B1/C1/D1, with original payload missingness preserved.

DataFrame.sort_values supports ordering by multiple labels. Its documentation also warns that the kind sorting-algorithm option is only applied to DataFrames when sorting a single column or label. Therefore this laboratory does not claim that specifying a “stable” kind would establish a general multi-column tie policy.

No tie resolution is needed here because (group, seq) is admitted as unique. If that condition fails, the source is not qualified for this selector until an owner supplies an ordering rule.

Retain all three artifacts: the reversed source, the unapproved F07 candidate, and the corrected F08 candidate. Do not overwrite the failed candidate and thereby erase evidence.

Most importantly, do not “repair” A1 by filling its missing quantity from A2. Preserving source semantics sometimes requires leaving a field unknown. The same broader discipline appears in Refonte Learning’s discussion of how to preserve explicit clear instructions: missing storage needs an approved meaning rather than an opportunistic substitute.

Prove display indexes are not record identities

F09 keeps every source record and unique row_id, but deliberately gives every row the same display-index label:

indexed = build_frame()
indexed.index = pd.Index([0] * len(indexed), name="display_index")

candidate = grouped(indexed).nth(0, dropna=None)

Expected selected identities remain A1/B1/C1/D1, while all four selected rows carry index label 0.

That is why an index lookup such as “the candidate came from index 0” is insufficient provenance. Index labels can be duplicated; the source contract in this laboratory uses the unique row_id plus complete tuple comparison.

For evidence, retain both:

evidence_index = candidate.index.tolist()
evidence_rows = candidate[COLUMNS].copy(deep=True)

The expected evidence_index is [0, 0, 0, 0]. That repetition is not an error to clean away. It is the point of the test: display index and record identity are different concepts.

The result should still undergo the same tuple reconciliation against the authoritative raw records. If the validator uses row_id and every field, repeated index labels are harmless. If it relies on ambiguous index lookup, F09 exposes the weakness.

Stop ambiguous identities before transformation

F10 modifies only one source identifier:

duplicate_id_rows = list(ROWS)
duplicate_id_rows[1] = ("A1", "A", 2, 10, None)

Now two distinct A records claim row_id="A1".

The admission guard must stop before any GroupBy transformation. The expected decision is HOLD_AMBIGUOUS_SOURCE; expected candidate is absent; expected transformation-call count is zero.

A runnable guard can make that sequence explicit:

def run_with_transform_counter(rows, transform):
    calls = 0
    df = build_frame(rows)
    try:
        admit_source(df)
    except ValueError as exc:
        return {
            "candidate": None,
            "transformation_calls": calls,
            "decision": "HOLD_AMBIGUOUS_SOURCE"
            if "row_id" in str(exc)
            else "UNQUALIFIED_INPUT",
            "error": str(exc),
        }
    calls += 1
    candidate = transform(df)
    return {
        "candidate": candidate,
        "transformation_calls": calls,
        "decision": None,
        "error": None,
    }

This is an authored guard expectation, not a claim that pandas itself raises a special identity exception. pandas has no reason to know that this application treats row_id as authoritative.

The same admission boundary should reject missing required columns, unsupported dtypes, null group/order fields, and duplicate (group, seq) pairs. Those conditions are unqualified inputs, not additional behavioral cases. Do not silently deduplicate them, infer a tie breaker, or coerce them into this test contract.

Capture evidence and reconcile all ten cases

A useful test harness separates planned expectations from future observations. The following laboratory is executable, but execution remains disabled by default: EXECUTE_CASES = False. Running it without changing that setting does not turn expected outcomes into observations.

from future import annotations
import json
import platform
from datetime import datetime, timezone
from importlib import metadata
import pandas as pd
from pandas.testing import assert_frame_equal
SCRIPT_REVISION = "groupby-first-source-record-r1"
EXECUTE_CASES = False
ROWS = [
    ("A1", "A", 1, None, "open"),
    ("A2", "A", 2, 10, None),
    ("A3", "A", 3, 20, "closed"),
    ("B1", "B", 1, 7, "ready"),
    ("B2", "B", 2, 9, "later"),
    ("C1", "C", 1, None, None),
    ("C2", "C", 2, None, None),
    ("D1", "D", 1, None, "held"),
    ("D2", "D", 2, 4, None),
]

COLUMNS = ["row_id", "group", "seq", "qty", "state"]
FIRST_EVENT = {
    "A": ("A1", "A", 1, None, "open"),
    "B": ("B1", "B", 1, 7, "ready"),
    "C": ("C1", "C", 1, None, None),
    "D": ("D1", "D", 1, None, "held"),
}
FIRST_COMPLETE = {
    "A": ("A3", "A", 3, 20, "closed"),
    "B": ("B1", "B", 1, 7, "ready"),
}
EXPECTED = {

    "F01": {"ids": ["B1"], "decision": "ACCEPT_SOURCE_ROW"},

    "F02": {
        "ids": ["A1", "B1", "C1", "D1"],
        "decision": "REJECT_SYNTHETIC_RECORD",
    },

    "F03": {
        "ids": ["A1", "B1", "C1", "D1"],
        "decision": "ACCEPT_SOURCE_ROW",
    },

    "F04": {
        "ids": ["A1", "B1", "C1", "D1"],
        "decision": "ACCEPT_SOURCE_ROW",
    },

    "F05": {
        "ids": ["A1", "B1", "C1", "D1"],
        "decision": "ACCEPT_SOURCE_ROW",
    },

    "F06": {
        "ids": ["A3", "B1"],
        "decision": {
            "A": "ACCEPT_SOURCE_ROW:first-complete-policy",
            "B": "ACCEPT_SOURCE_ROW:first-complete-policy",
            "C": "HOLD_NO_COMPLETE_RECORD",
            "D": "HOLD_NO_COMPLETE_RECORD",
        },
    },

    "F07": {
        "ids": ["D2", "C2", "B2", "A3"],
        "decision": "HOLD_SELECTION_POLICY",
    },

    "F08": {
        "ids": ["A1", "B1", "C1", "D1"],
        "decision": "ACCEPT_SOURCE_ROW",
    },

    "F09": {
        "ids": ["A1", "B1", "C1", "D1"],
        "decision": "ACCEPT_SOURCE_ROW",
    },

    "F10": {
        "ids": None,
        "decision": "HOLD_AMBIGUOUS_SOURCE",
        "transformation_calls": 0,
    },
}
def build_frame(rows=ROWS):
    return pd.DataFrame(rows, columns=COLUMNS).astype({
        "row_id": "string[python]",
        "group": "string[python]",
        "seq": "int64",
        "qty": "Int64",
        "state": "string[python]",
    })
def grouped(df, *, sort=False):
    return df.groupby(
        "group",
        sort=sort,
        dropna=False,
        observed=True,
    )
def admit_source(df):
    if list(df.columns) != COLUMNS:
        raise ValueError("Unsupported source columns")
    if df["row_id"].isna().any() or (df["row_id"].str.len() == 0).any():
        raise ValueError("row_id missing or empty")
    if not df["row_id"].is_unique:
        raise ValueError("row_id ambiguous")
    if df["group"].isna().any() or df["seq"].isna().any():
        raise ValueError("group/seq missing")
    if df.duplicated(["group", "seq"]).any():
        raise ValueError("sequence tie")
def norm_scalar(value):
    if pd.isna(value):
        return None
    if hasattr(value, "item") and not isinstance(value, str):
        return value.item()
    return value
def normalized_records(df):
    return [
        tuple(norm_scalar(x) for x in row)
        for row in df[COLUMNS].itertuples(index=False, name=None)
    ]
def normalize_first(result):
    return result.reset_index()[COLUMNS]
def preserve_check(before, after):
    assert_frame_equal(
        before,
        after,
        check_exact=True,
        check_dtype=True,
    )
def run_cases():
    reports = {}

    # F01
    df = build_frame([ROWS[3], ROWS[4]])
    raw = df.copy(deep=True)
    c = normalize_first(
        grouped(df).first(
            numeric_only=False,
            min_count=-1,
            skipna=True,
        )
    )
    preserve_check(raw, df)
    reports["F01"] = normalized_records(c)
    # F02
    df = build_frame()
    raw = df.copy(deep=True)
    c = normalize_first(
        grouped(df).first(
            numeric_only=False,
            min_count=-1,
            skipna=True,
        )
    )
    preserve_check(raw, df)
    reports["F02"] = normalized_records(c)

    # F03
    df = build_frame()
    raw = df.copy(deep=True)
    c = normalize_first(
        grouped(df).first(
            numeric_only=False,
            min_count=-1,
            skipna=False,
        )
    )
    preserve_check(raw, df)
    reports["F03"] = normalized_records(c)
    # F04
    df = build_frame()
    raw = df.copy(deep=True)
    c = grouped(df).nth(0, dropna=None)
    preserve_check(raw, df)
    reports["F04"] = normalized_records(c)
    # F05
    df = build_frame()
    raw = df.copy(deep=True)
    c = grouped(df).head(1)
    preserve_check(raw, df)
    reports["F05"] = normalized_records(c)
    # F06: both approved comparison paths
    df = build_frame()
    raw = df.copy(deep=True)
    via_nth = grouped(df).nth(0, dropna="any")
    eligible = df.dropna(
        subset=["qty", "state"],
        how="any",
    )
    via_explicit = grouped(eligible).nth(0, dropna=None)
    preserve_check(raw, df)
    reports["F06"] = {
        "nth_dropna_any": normalized_records(via_nth),
        "explicit_payload_dropna": normalized_records(via_explicit),
    }
    # F07: reversed encounter order, including sort=True comparison
    df = build_frame(list(reversed(ROWS)))
    raw = df.copy(deep=True)
    unsorted_groups = grouped(df).nth(0, dropna=None)
    sorted_group_keys = df.groupby(
        "group",
        sort=True,
        dropna=False,
        observed=True,
    ).nth(0, dropna=None)
    preserve_check(raw, df)
    reports["F07"] = {
        "sort_false": normalized_records(unsorted_groups),
        "sort_true": normalized_records(sorted_group_keys),
    }
    # F08
    df = build_frame(list(reversed(ROWS)))
    raw = df.copy(deep=True)
    ordered = df.sort_values(["group", "seq"])
    c = grouped(ordered).nth(0, dropna=None)
    preserve_check(raw, df)
    reports["F08"] = normalized_records(c)
    # F09
    df = build_frame()
    df.index = pd.Index([0] * len(df), name="display_index")
    raw = df.copy(deep=True)
    c = grouped(df).nth(0, dropna=None)
    preserve_check(raw, df)
    reports["F09"] = {
        "records": normalized_records(c),
        "raw_index": c.index.tolist(),
    }
    # F10
    rows = list(ROWS)
    rows[1] = ("A1", "A", 2, 10, None)
    df = build_frame(rows)
    calls = 0
    try:
        admit_source(df)
        calls += 1
        = grouped(df).nth(0, dropna=None)
    except ValueError as exc:
        reports["F10"] = {
            "candidate": None,
            "transformationcalls": calls,
            "error": str(exc),
        }
    return reports
def execution_record():
    base = {
        "script_revision": SCRIPT_REVISION,
        "python": platform.python_version(),
        "pandas": metadata.version("pandas"),
        "numpy": metadata.version("numpy"),
        "executed": False,
        "observed": None,
        "execution_state": "EXPECTED / NOT EXECUTED",
    }
    if not EXECUTE_CASES:
        return base
    observed = run_cases()
    if set(observed) != set(EXPECTED):
        raise RuntimeError("Missing or duplicate case coverage")
    base.update({
        "executed": True,
        "observed": observed,
        "execution_state": "RECORDED EXECUTION",
        "run_utc": datetime.now(timezone.utc).isoformat(),
    })
    return base
if name == "__main__":
    print(json.dumps(execution_record(), indent=2, default=str))

The case manifest is therefore:

Case

Input variant

Operation

Expected IDs / fields

Coherence expectation

Policy decision

Execution state

F01

B1/B2 ordered

first(skipna=True)

B1 = 7 / ready

intact B1

ACCEPT_SOURCE_ROW

EXPECTED / NOT EXECUTED

F02

all rows ordered

first(skipna=True)

A1 with qty 10; B1; C1; D1 with qty 4

A/D synthetic; B/C intact

REJECT_SYNTHETIC_RECORD overall

EXPECTED / NOT EXECUTED

F03

all rows ordered

first(skipna=False)

A1/B1/C1/D1 incl. original NA

all intact

ACCEPT_SOURCE_ROW

EXPECTED / NOT EXECUTED

F04

all rows ordered

nth(0, dropna=None)

A1/B1/C1/D1

all intact

ACCEPT_SOURCE_ROW

EXPECTED / NOT EXECUTED

F05

all rows ordered

head(1)

A1/B1/C1/D1

all intact

ACCEPT_SOURCE_ROW

EXPECTED / NOT EXECUTED

F06

all rows

nth(...dropna="any") and payload dropna path

A3/B1; no C/D

selected rows intact

A/B accepted only under complete policy; C/D HOLD_NO_COMPLETE_RECORD

EXPECTED / NOT EXECUTED

F07

reversed

nth(0); compare sort=False/True

D2/C2/B2/A3

all intact

HOLD_SELECTION_POLICY

EXPECTED / NOT EXECUTED

F08

reversed then sort group,seq

nth(0)

A1/B1/C1/D1

all intact

ACCEPT_SOURCE_ROW

EXPECTED / NOT EXECUTED

F09

all index labels = 0

nth(0)

A1/B1/C1/D1; indexes 0/0/0/0

all intact

ACCEPT_SOURCE_ROW

EXPECTED / NOT EXECUTED

F10

A2 renamed A1

admission guard

no candidate; calls = 0

identity unresolved

HOLD_AMBIGUOUS_SOURCE

EXPECTED / NOT EXECUTED


Distinguish authored expectations from recorded observations

Until somebody actually runs the script and retains its artifacts, the correct evidence fields are:

{
  "executed": false,
  "observed": null,
  "execution_state": "EXPECTED / NOT EXECUTED"
}

A future execution should add the actual Python, pandas, and NumPy versions; UTC run identity; script revision; raw source; raw candidate frames; dtype metadata; index metadata; donor ledger; per-case findings; exceptions; and the exact set of case IDs present.

Completion checking should require exactly F01–F10. A missing case is incomplete evidence; a duplicate case is ambiguous evidence. Neither should be silently accepted.

Most importantly, never populate observed by copying the expected manifest. Expected values are an oracle written before execution. Observed values must come from the retained run. A mismatch is evidence to investigate, not something to normalize away to create a PASS.

Assign acceptance, recovery, and rollback ownership

A production review should translate technical findings into explicit decisions rather than one undifferentiated “works/doesn’t work” flag.

Finding

Meaning

Decision

Primary owner

Candidate equals raw tuple and matches approved first ID

Coherent first event

ACCEPT_SOURCE_ROW

reviewer + data owner

Per-column values intentionally summarize different donors

Legitimate summary, not an event

AGGREGATE_ONLY

data owner

Claimed ID exists but candidate fields do not equal that row

Synthetic tuple

REJECT_SYNTHETIC_RECORD

transformation engineer

Candidate is genuine but not sequence-first

Order contract violated

HOLD_SELECTION_POLICY

data owner + engineer

Complete-record policy has no qualifying row

Absence is real under that policy

HOLD_NO_COMPLETE_RECORD

data owner

Source identity is duplicated or unresolved

Provenance cannot be established

HOLD_AMBIGUOUS_SOURCE

source/data owner

The data owner approves semantics: what “first” means, whether payload missingness is allowed, and whether a first-complete policy is ever valid. The transformation engineer implements that contract without erasing raw evidence. The reviewer independently checks tuple coherence, order, schemas, and test coverage. The downstream report owner identifies reports, extracts, models, or consumers that received an affected output and controls replacement publication.

Recovery should start from retained raw events and the approved selector. Do not repair a synthetic A record by taking A1 and adding A2’s quantity; that merely institutionalizes the same donor mixing under a different code path. Rebuild the candidate from source rows.

Likewise, a code rollback is not semantic proof. Rolling back to a previous revision is justified only when that revision’s selector, schema assumptions, ordering policy, and evidence are known to be qualified for the affected population. If an old version used the same mistaken “first event” interpretation, restoring it changes code without restoring meaning.

Retain both the rejected evidence and the replacement output. Identify affected consumers, republish separately, and document which contract authorized the replacement. Acceptance remains bounded by this five-column schema, the pandas 2.2.3 reference behavior, the fixture and variants reviewed, and the application policies written above. It should not be generalized to joins, timestamps, categorical expansion, imputation, distributed engines, or untested pandas releases.

Develop pipeline foundations with Refonte Learning Data Engineering

Whole-record validation is one small example of a broader data-engineering discipline: define transformation semantics, retain source evidence, make ordering explicit, and test whether outputs preserve the meaning promised to downstream consumers.

Refonte Learning’s Data Engineering program currently lists a program-specific period of 3 months and 12–14 hours per week, with admission requiring students to be working toward a bachelor’s or higher-level degree. Its published curriculum previews introduction to data engineering, warehousing and ETL, and big-data technologies and pipeline design; Hadoop and Spark are named explicitly. The page also describes transformation and governance areas, an educational mentor, mentorship and virtual-internship opportunities, and Training Certificate and Certificate of Internship credentials upon successful completion. Those are program-page claims, not guarantees of employment or internship placement.

For readers building broader pipeline and transformation foundations, this program offers a next step.