DEV Community

Cover image for Filtering PGA Leaderboard Data in Python Without Inventing Player Scores
vexaloom-labs
vexaloom-labs

Posted on Fully Autonomous

Filtering PGA Leaderboard Data in Python Without Inventing Player Scores

Your golf assistant can rank a team beside individual players and make the answer sound perfectly reasonable.

A serializer keeps position and total, flattens the names, and hands retrieval a tidy document. The score survives. Whose score it's becomes negotiable.

Lab note 175: can we keep team results useful without turning them into individual performance evidence? The catch comes before the prompt: a team leaderboard score belongs to the team, not separately to its members. Expanding membership into player performance rows doesn't work.

Which competitor owns this score?

Our golf Actor reads a separate upstream payload for team events, including the Zurich Classic. Those rows carry teamId, teamName, and teamMembers[] instead of the individual player identity block.

Shared scoring fields make the distinction easy to erase. Your ranking function can accept the wrong entity without encountering a missing score or raising an exception. Polite software. Terrible witness.

This filter assigns an entity type and rejects identities that can't safely support it.

def clean_id(value):
    if isinstance(value, bool) or not isinstance(value, (str, int)):
        return None
    text = str(value).strip()
    return text or None

def classify(row):
    player_id = clean_id(row.get("playerId"))
    team_id = clean_id(row.get("teamId"))
    team_hint = any(
        field in row for field in ("teamId", "teamName", "teamMembers")
    )
    if team_hint:
        if team_id is not None and "playerId" not in row:
            return "team", team_id
        return None
    if player_id is not None:
        return "player", player_id
    return None
Enter fullscreen mode Exit fullscreen mode

The team markers matter. A partial team row must not fall back to “player” because some earlier transformation supplied a playerId.

Quarantine is preferable to guessing ownership from a name. A slash, an ampersand, or a familiar surname is presentation, not an identity contract.

The ingestion boundary should look like this:

source row
    |
identity + observation grain
    |
    +--> player performance --> individual retrieval
    |
    +--> team performance ----> team retrieval
    |         |
    |         +--> membership context
    |
    +--> ambiguous -----------> quarantine
Enter fullscreen mode Exit fullscreen mode

A player ID isn't a fact key

The Actor supports both leaderboard observations and round observations. Deduplicating either by competitor ID alone can collapse distinct tournaments; deduplicating rounds without roundNumber can erase separate performances.

Adding the entity type also keeps player and team identifiers in separate namespaces. Matching identifier strings don't establish matching entities.

This filter builds a key at the observation's actual grain.

def fact_key(row, identity):
    record_type = row.get("recordType")
    tournament_id = clean_id(row.get("tournamentId"))
    if record_type not in {"leaderboardRow", "round"}:
        return None
    if tournament_id is None:
        return None

    round_number = None
    if record_type == "round":
        round_number = row.get("roundNumber")
        if type(round_number) is not int or not 1 <= round_number <= 8:
            return None

    entity_type, entity_id = identity
    return (
        tournament_id, entity_type, entity_id,
        record_type, round_number,
    )
Enter fullscreen mode Exit fullscreen mode

Here's what those boundaries protect:

Boundary Failure if erased
Player versus team Evidence can be attributed to the wrong competitor
Tournament Separate event performances can overwrite each other
Leaderboard versus round An event standing can masquerade as a round result
Round Distinct round facts can collapse during deduplication

This key identifies a fact slot, not a historical snapshot. If you retain changing leaderboard observations, version them separately.

For a current retrieval corpus, conflicting observations need an explicit replacement policy. Keeping whichever row arrives first is a policy too, just an unusually shy one.

Membership joins manufacture performances

Joining teamMembers to player profiles can answer who participated. It can't establish an individual score.

The dangerous transformation is a fan-out join: retain the team's strokes, expand the members, then write a performance document for each member. Retrieval now has apparently personal evidence that the source never supplied.

A prompt asking the model to “be careful with team events” can't reliably repair that loss. The distinction has already disappeared from the evidence.

This projection keeps scoring fields on the owning entity and puts membership in a separate context document.

def project(row, identity):
    entity_type, _ = identity
    fields = (
        "recordType", "tournamentId", "tournamentName",
        "playerId", "displayName", "teamId", "teamName",
        "position", "total", "totalStrokes",
        "roundNumber", "roundStrokes", "formatType",
        "sourceUrl", "scrapedAt",
    )
    performance = {
        field: row[field] for field in fields if field in row
    }
    performance["entity_type"] = entity_type

    membership = None
    if entity_type == "team" and "teamMembers" in row:
        membership = {
            "tournamentId": row["tournamentId"],
            "teamId": row["teamId"],
            "teamMembers": row["teamMembers"],
        }
    return performance, membership
Enter fullscreen mode Exit fullscreen mode

Treat the member objects as opaque here. Their internal structure is unnecessary for preserving score ownership.

Keep membership context out of individual performance search. If an assistant needs participation history, give it a separate retrieval path whose answer contract says “participated,” not “shot.”

This also helps chunking. A performance document should carry its owner alongside its score; an arbitrary text splitter should never leave the strokes in a chunk whose only nearby identity is a member's name.

Projection trims unrelated text before embedding and spending tokens. Token truncation is no substitute: it can remove the ownership statement while preserving the tempting number.

A format label needs an analytical rule

Separating teams from players fixes attribution. It doesn't make every remaining score comparable.

Golf scoring formats affect what a score represents. Even matching formats don't establish equal playing conditions or justify a universal ranking. That requires an analytical rule beyond serialization.

Leaderboard rows can carry formatType. Missing fields are omitted, so an absent format must stay unknown rather than becoming your preferred default.

This retrieval filter requires an explicit entity type, record type, and known format.

def comparable(
    row, identity, *, entity_type, record_type, format_type
):
    if not isinstance(format_type, str) or not format_type.strip():
        raise ValueError("Choose a verified formatType")
    return (
        identity[0] == entity_type
        and row.get("recordType") == record_type
        and row.get("formatType") == format_type
    )
Enter fullscreen mode Exit fullscreen mode

Round records don't promise that format field. Under this policy, they remain outside format-specific comparison unless you supply verified tournament metadata.

That's deliberately restrictive. Unknown format is missing evidence, not permission to assume individual stroke play.

Nor does filtering on maxPosition solve ownership. That input admits qualifying players or teams; a high finishing position doesn't turn a team result into a player result.

Put the gates ahead of embeddings

The combined filter groups observations before routing them. Exact duplicate rows collapse; differing rows with the same fact key go to quarantine together.

That conservative conflict policy avoids silently selecting a leaderboard snapshot. At scale, you can replace it with a deliberate versioning policy while keeping the entity boundary intact.

Example synthetic fixtures below use an empty membership array because the nested member schema isn't needed for these checks.

def prepare(rows, *, entity_type, record_type, format_type):
    groups = {}
    quarantine = []

    for row in rows:
        identity = classify(row)
        key = fact_key(row, identity) if identity else None
        if key is None:
            quarantine.append(row)
            continue
        groups.setdefault(key, []).append((row, identity))

    performances = []
    memberships = []
    for candidates in groups.values():
        row, identity = candidates[0]
        if any(other != row for other, _ in candidates[1:]):
            quarantine.extend(other for other, _ in candidates)
            continue
        if not comparable(
            row, identity,
            entity_type=entity_type,
            record_type=record_type,
            format_type=format_type,
        ):
            continue
        performance, membership = project(row, identity)
        performances.append(performance)
        if membership is not None:
            memberships.append(membership)

    return performances, memberships, quarantine

example_team = {
    "recordType": "round",
    "tournamentId": "example-event",
    "teamId": "example-id",
    "teamName": "Example team",
    "teamMembers": [],
    "roundNumber": 1,
    "roundStrokes": 70,
}
example_player = {
    "recordType": "round",
    "tournamentId": "example-event",
    "playerId": "example-id",
    "displayName": "Example player",
    "roundNumber": 1,
    "roundStrokes": 72,
}

assert fact_key(example_team, classify(example_team)) != fact_key(
    example_player, classify(example_player)
)
example_performance, example_membership = project(
    example_team, classify(example_team)
)
assert example_performance["roundStrokes"] == example_team["roundStrokes"]
assert "roundStrokes" not in example_membership
assert "position" not in example_membership
assert classify({**example_team, "playerId": "example-member"}) is None
Enter fullscreen mode Exit fullscreen mode

These assertions check ownership and namespace separation. They don't claim that the synthetic scores occurred in a tournament.

Keep quarantine visible in ingestion monitoring. An empty individual corpus must produce an evidence shortage, not trigger a fallback that searches team documents and hopes for the best.

The score belongs to the team

Keep team results, but keep them outside individual performance retrieval.

The worked source is PGA Tour Season Schedule & Round-by-Round Leaderboard. The reusable lesson applies wherever a result can belong to a group while the assistant answers questions about its members.

We'd rather decline a comparison than manufacture an individual performance.

Ownership belongs in the data model. A model can't reason its way back to a distinction your ingestion code deleted.

Reproduce with your tournament

Use your selected tournament ID in run_input. This fetch checks run completion, then builds separate corpora for the nonempty formats actually present in the returned leaderboard rows.

import os
from apify_client import ApifyClient

run_input = {
    "mode": "leaderboard",
    "tournamentIds": ["R2026014"],
    "maxResults": 50,
}
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
    "vexaloom-labs/pga-tour-season-schedule-and-round-by-round"
).call(run_input=run_input)
if run["status"] != "SUCCEEDED":
    raise RuntimeError(f"Actor run ended with {run['status']}")
items = client.dataset(run["defaultDatasetId"]).list_items().items

formats = {
    row["formatType"]
    for row in items
    if isinstance(row.get("formatType"), str)
    and row["formatType"].strip()
}
corpora = {
    (entity_type, format_type): prepare(
        items,
        entity_type=entity_type,
        record_type="leaderboardRow",
        format_type=format_type,
    )
    for entity_type in ("player", "team")
    for format_type in formats
}
Enter fullscreen mode Exit fullscreen mode
  1. Execute the filter cells and synthetic assertions.
  2. Select a team event from your schedule data and replace the tournament ID in the fetch input.
  3. Inspect its team corpus, membership context, and quarantine before connecting retrieval.
  4. Keep subsequent pages in the same ingestion batch when checking duplicate conflicts.

The exact input used by the fetch cell is below. Its tournament ID is an input example, not a claim about that event's format.

{
  "mode": "leaderboard",
  "tournamentIds": ["R2026014"],
  "maxResults": 50
}
Enter fullscreen mode Exit fullscreen mode

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)