PSA data in Python: correct counts can still change your year chart

2026-11-28来源 dev.toEnglish

You replace stored set URLs with shorter numeric IDs, rebuild the year chart, and the vintage mix shifts. Now you've to explain whether the cards changed or the pipeline did.

A bare headingId returns correct population counts but can't supply the set name or year. The Actor needs setUrls to supply that metadata.

That distinction reaches straight into df.groupby("setYear"): pandas excludes missing grouping keys by default. Your population totals can survive collection while some of the cards carrying them disappear from the chart.

Which records belong in the cohort?

The question isn't just whether a count is correct. It's whether the record carrying that count has enough metadata to enter the comparison you intend to publish.

A year chart needs both the population measure and a release-year assignment. Those are separate coverage questions.

We can make the distinction visible without assuming either is complete. Example input below requests a set through its numeric ID and leaves out the optional set-total row.

import os from urllib.parse import urlsplit import pandas as pd from apify_client import ApifyClient run_input = { "mode": "setPopulation", "headingIds": ["49722"], "includeSetTotal": False, "maxItems": 5000, } client = ApifyClient(os.environ["APIFY_TOKEN"]) run = client.actor("dataspryva/psa-card-grade-population-lookup").call( run_input=run_input ) if run["status"] != "SUCCEEDED": raise RuntimeError(f"Collection ended with status {run['status']}") items = [] for item in client.dataset(run["defaultDatasetId"]).iterate_items(): items.append(item) 

The streaming iterator avoids making a dataset page look like the whole pull. It doesn't remove the Actor's collection cap.

The lookup route is part of the pull

A numeric identifier identifies the set. It doesn't carry the descriptive context supplied by a population URL.

That creates a split worth keeping in your analysis:

set URL -> population counts + supplied set metadata -> year cohort bare ID -> population counts -> metadata needed 

Keep a request manifest alongside the returned records. It lets you distinguish unavailable year metadata from a failed match between your request and your dataset.

This cell builds that manifest from the actual input, preserving identifiers as strings.

manifest = pd.DataFrame( [ { "headingId": urlsplit(url).path.rstrip("/").rsplit("/", 1)[-1], "lookup_route": "setUrls", } for url in run_input.get("setUrls", []) ] + [ {"headingId": str(value), "lookup_route": "headingIds"} for value in run_input.get("headingIds", []) ], columns=["headingId", "lookup_route"], ).astype("string").drop_duplicates() if manifest["headingId"].duplicated().any(): raise ValueError("Request each set through a single route per pull.") 

For a route comparison, keep each pull separate. Mixing snapshots would introduce another explanation for changed counts before you've resolved the metadata question.

Coverage starts before the year field

The collection boundary matters before pandas sees anything. Here are the parts that affect this comparison.

Boundary What it means for the year chart
Requested sets A set pull covers the supplied sets, rather than a geographically defined sample or the whole collectible catalogue.
Categories Collectible categories aren't geographic labels. Category composition needs its own check before comparing release cohorts.
Collection cap maxItems stops collection after the selected number of records. Reaching it doesn't establish that the requested sets were exhausted.
Filters Subject, variety, total-population and grade-population filters can narrow the cards represented within a set.
Population line isPsaDna selects the certified population line instead of the standard card population. Keep that choice consistent across pulls.
Conditional metadata Empty source fields are omitted. Missing keys need to become explicit missing values in your analysis.
Row types Optional set totals and lookup errors aren't card identities. Neither belongs in the card-level denominator.

The code below separates those row types, quarantines records without usable identifiers, and parses formatted population totals. An absent or unparseable total stays missing.

columns = [ "headingId", "specId", "setName", "setYear", "totalGraded", "recordType", "error", ] records = pd.DataFrame.from_records(items).reindex(columns=columns) for field in ("headingId", "specId", "setName", "setYear"): records[field] = ( records[field].astype("string").str.strip().replace("", pd.NA) ) error_rows = ( records["error"].astype("string").str.strip().fillna("").ne("") ) set_total_rows = ( records["recordType"].astype("string").eq("setTotal").fillna(False) ) candidates = records.loc[~error_rows & ~set_total_rows].copy() missing_identity = candidates[["headingId", "specId"]].isna().any(axis=1) quarantined = candidates.loc[missing_identity].copy() cards = candidates.loc[~missing_identity].copy() numeric_total = pd.to_numeric( cards["totalGraded"].astype("string") .str.replace(",", "", regex=False) .str.strip(), errors="coerce", ) cards["totalGraded"] = numeric_total.where( numeric_total.ge(0) & numeric_total.mod(1).eq(0) ).astype("Int64") if cards.duplicated(["headingId", "specId"]).any(): raise ValueError("Repeated card identities need resolution before aggregation.") cards = cards.merge(manifest, on="headingId", how="left", validate="many_to_one") cards["lookup_route"] = cards["lookup_route"].fillna("not_in_manifest") pull_audit = pd.Series({ "error_rows": int(error_rows.sum()), "set_total_rows": int(set_total_rows.sum()), "quarantined_rows": len(quarantined), "rows_without_manifest_match": int( cards["lookup_route"].eq("not_in_manifest").sum() ), }) 

The identity check uses the set and spec identifiers together. Silently dropping repeated identities would hide whether you combined overlapping pulls, repeated a request, or mixed snapshots.

An unexplained duplicate isn't a spare card.

Count identities and the populations they represent

Missing-year coverage needs more than a row percentage.

Each card identity carries a population total. A metadata gap can affect relatively few identities while excluding a substantial share of the graded population represented in your pull.

This cell measures year availability by lookup route, with separate denominators for identities and usable population totals.

coverage = ( cards.assign(year_assigned=cards["setYear"].notna()) .groupby(["lookup_route", "year_assigned"], dropna=False) .agg( card_identities=("specId", "size"), identities_with_total=("totalGraded", "count"), known_totalGraded=( "totalGraded", lambda values: values.sum(min_count=1) ), ) .reset_index() ) 

Inspect coverage alongside pull_audit. The former describes eligible card records; the latter shows records that couldn't enter that analysis.

known_totalGraded deliberately sums only available numeric totals. The companion count tells you how many identities contributed to that sum. Missing totals don't become zero merely because a chart prefers tidy arithmetic.

This measures coverage within your pull. It can't measure cards that collection never reached.

Where pandas can shrink the denominator

The default year grouping can produce a perfectly plausible chart from a restricted subset of your records.

Keep the inclusive grouping for the audit, even if the published chart eventually shows assigned years alone. A missing-year bucket is an accounting boundary, not a release cohort.

This cell builds both versions and isolates the records omitted by the default grouping.

default_years = cards.groupby("setYear").agg( card_identities=("specId", "size"), known_totalGraded=("totalGraded", lambda values: values.sum(min_count=1)), ) inclusive_years = cards.groupby("setYear", dropna=False).agg( card_identities=("specId", "size"), known_totalGraded=("totalGraded", lambda values: values.sum(min_count=1)), ) unassigned = cards.loc[cards["setYear"].isna()] chart_omissions = pd.Series({ "card_identities": len(unassigned), "identities_with_total": int(unassigned["totalGraded"].notna().sum()), "known_totalGraded": unassigned["totalGraded"].sum(min_count=1), }) 

chart_omissions gives you the denominator excluded during chart construction. It doesn't establish why each year is unavailable; the request route and retained records provide that context.

Keeping the unassigned bucket also makes comparisons between pipeline versions defensible. Otherwise, apparent movement between vintage cohorts can partly reflect which records still have labels.

Enrich without multiplying the census

A maintained set dimension separates descriptive metadata from repeated population collection.

The PSA Card Grade Population Lookup supplies the population records; your dimension supplies checked metadata keyed by headingId. That separation is useful when your stored requests already use numeric IDs.

The join needs a strict relationship. Repeated dimension keys can multiply card rows and their population totals, turning a metadata repair into a larger census.

Example dimension below supplies metadata for the requested set; replace its entries with metadata you've checked.

set_dimension = pd.DataFrame( [{"headingId": "49722", "setName": "Topps", "setYear": "1952"}], dtype="string", ) enriched = cards.merge( set_dimension, on="headingId", how="left", suffixes=("", "_dim"), validate="many_to_one", sort=False, ) assert len(enriched) == len(cards) pd.testing.assert_series_equal( enriched["totalGraded"].reset_index(drop=True), cards["totalGraded"].reset_index(drop=True), ) conflict_mask = pd.Series(False, index=enriched.index) for field in ("setName", "setYear"): existing = enriched[field] supplied = enriched[f"{field}_dim"] conflict_mask |= ( existing.notna() & supplied.notna() & existing.ne(supplied) ).fillna(False) enriched[field] = existing.combine_first(supplied) metadata_conflicts = enriched.loc[conflict_mask].copy() enriched_years = enriched.groupby("setYear", dropna=False).agg( card_identities=("specId", "size"), known_totalGraded=("totalGraded", lambda values: values.sum(min_count=1)), ) 

The assertion checks every retained population total, which also protects their aggregate. The join validation rejects repeated dimension keys before they can inflate the chart.

Existing metadata wins here; the dimension fills gaps. metadata_conflicts retains disagreements for review rather than silently moving already assigned cards into different cohorts.

Keep the dimension version with the analysis. A future metadata correction can legitimately change cohort membership without changing the collected counts.

State the boundary beside the chart

A defensible caption names the population being summed and the collection boundary.

For this analysis, that means graded population by set release year, limited to the requested sets and applied filters. State whether unassigned years appear in the chart, and report their identity count and known population total from the audit.

If collection reached its cap, describe the pull as capped. Metadata completeness can't turn a truncated collection into a complete set census.

Retain the request input, request manifest, dataset identifier and enrichment version with the report. Those artefacts let you explain which boundary changed when a later chart differs.

Release years aren't grading dates

setYear describes a card set's release cohort. It doesn't tell you when its copies were graded, where their owners live, or how many ungraded copies exist.

scrapedAt records collection timing, not a grading history. There's no public recently graded feed behind the removed recentGrades mode.

A year chart can describe the release cohorts represented in a grading population. It can't turn those cohorts into a history of grading activity.

A correct count still needs a defensible place to belong.

Drafted with AI assistance and reviewed for accuracy.

原文:https://www.a8q9.cn/en/article/psa-data-in-python-correct-counts-can-still-change-your-year-chart-b04ab1.html

相关文章