Enrich an NPI roster with Part D activity in Python

Join a provider roster to specialty, claims, generic share and a specialty benchmark using genuine samples and copyable Python.

Add Part D activity to an NPI roster

You have a provider roster identified by NPI and want to add published specialty, location and prescription activity. This example selects three North Carolina prescribers classified as Family Practice in the 2024 CMS provider summary. It joins by NPI and adds a benchmark for their exact specialty and specialty source.

The optional input.csv contains those three genuine NPI selections. The same selections appear in the roster list in the Python code below. There is no invented clinic, patient record or prescribing observation.

Download prescribers.csv and specialty_summary.csv into your working folder. These are genuine subsets of the paid tables: three complete provider records and their matching specialty/source summary. The summary describes all 92,431 NPIs in that group, not just the three selected providers. The complete $29 product contains 1,416,883 NPI records with 46 fields, 277 specialty/source summaries and four documentation tables. Inspect the coverage and fields.

Code example

This code uses Python’s standard library and runs in a notebook cell, IPython or a script. It reads the provider CSV one row at a time, so it can use the full purchased file without loading the entire roster into memory.

Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.

Python 3.10+ · Jupyter, IPython or a script
import csv
from decimal import Decimal
from pathlib import Path

# Three genuine NPI selections, also supplied in the optional input.csv.
roster = [{'npi': '1053767749'}, {'npi': '1053768739'}, {'npi': '1053798660'}]
data_path = Path('prescribers.csv')
summary_path = Path('specialty_summary.csv')
selected = {r['npi'] for r in roster}
providers = {}
with data_path.open(encoding='utf-8', newline='') as f:
    for row in csv.DictReader(f):
        if row['npi'] in selected:
            providers[row['npi']] = row
with summary_path.open(encoding='utf-8', newline='') as f:
    specialties = {r['specialty_id']: r for r in csv.DictReader(f)}

results = []
for item in roster:
    row = providers.get(item['npi'])
    if row is None:
        print(f"{item['npi']}: absent from this source edition; no zero activity inferred.")
        results.append({**item, 'status': 'not_in_edition'})
        continue
    cohort = specialties[row['specialty_id']]
    generic_share = (f"{Decimal(row['generic_claim_share_percent']):.1f}%"
                     if row['generic_claim_share_percent_status'] == 'reported' else 'suppressed')
    cost_per_fill = Decimal(row['gross_cost_per_30day_fill'])
    benchmark = Decimal(cohort['gross_cost_per_30day_fill'])
    result = {**item, 'status': 'reported', 'name': ' '.join(filter(None, [row['first_name'], row['last_or_organization_name']])),
              'specialty': row['specialty'], 'specialty_source': row['specialty_source'],
              'city': row['city'], 'state': row['state'], 'claims': str(int(Decimal(row['total_claims']))),
              'generic_share': generic_share, 'gross_cost_per_30day_fill': f'{cost_per_fill:.2f}',
              'specialty_gross_cost_per_30day_fill': f'{benchmark:.2f}',
              'specialty_prescribers': cohort['prescriber_count']}
    results.append(result)
    print(f"{result['name']} | {row['city']}, {row['state']} | NPI {row['npi']}")
    print(f"  {row['specialty']} ({row['specialty_source']}): {int(Decimal(row['total_claims'])):,} claims; generic share {generic_share}")
    print(f"  Gross cost per 30-day fill: ${cost_per_fill:.2f}; specialty/source group: ${benchmark:.2f} ({int(cohort['prescriber_count']):,} NPIs)")

Replace roster with your own NPI strings or load the same column from a CSV. NPI is a provider identifier; a name, practice address or specialty alone is not the matching key.

Analysis of the output

Sean Vidulich | Greenville, NC | NPI 1053767749
  Family Practice (Claim-Specialty): 5,515 claims; generic share 86.6%
  Gross cost per 30-day fill: $20.29; specialty/source group: $44.12 (92,431 NPIs)
Eugene Wang | Charlotte, NC | NPI 1053768739
  Family Practice (Claim-Specialty): 1,726 claims; generic share 82.3%
  Gross cost per 30-day fill: $58.11; specialty/source group: $44.12 (92,431 NPIs)
Laura Gay | Durham, NC | NPI 1053798660
  Family Practice (Claim-Specialty): 1,254 claims; generic share 86.8%
  Gross cost per 30-day fill: $45.58; specialty/source group: $44.12 (92,431 NPIs)

The join adds each prescriber’s published name, city, specialty and 2024 Part D claim count. It also supplies generic claim share: generic claims divided by all claims attributed to that NPI. The three shares range from 82.3% to 86.8%. Claims include fills and refills; these are not counts of patients.

The specialty benchmark is $44.12 in gross drug cost per standardized 30-day fill. It is calculated as the group’s total cost divided by its total fills, rather than averaging individual provider ratios. These providers share the Claim-Specialty source, meaning CMS derived the specialty from Part B claims. A same-named specialty from another source remains a separate group.

Use the comparison to identify records for further investigation, not to rank care quality or prescribing efficiency. Differences can reflect drug mix, patient needs, coverage and attribution. Gross costs include multiple payers and do not subtract manufacturer rebates. The ratio is not a pharmacy price or a patient copay.

Suppressed generic claims produce a printed suppressed share. An NPI absent from this edition produces not_in_edition; neither result establishes zero activity. The specialty table reports how many NPIs have generic claims available and uses that same subset for its generic-share denominator. It does not reconstruct suppressed categories.

Using the full dataset

Extract the purchased ZIP and replace both sample CSVs with their complete counterparts. The code runs unchanged. prescribers.csv has one row per year and NPI, eleven original measures with reporting statuses, original suppression flags and two derived ratios.

There are 277 specialty/source groups, 96 reported country/state groups and an accounting row for every original provider record. source_fields.csv identifies all 84 source columns and which ones the product includes. Street addresses, beneficiary demographics and clinical drug categories are outside this reference’s scope.

Keep identifiers as text. CMS’s reported state abbreviation and state FIPS can disagree; neither is silently corrected. Postal ZIP is not a Census ZCTA. Names and locations come from a dated NPPES extract, so this is not a current contact directory. Beneficiaries can occur under multiple NPIs and must not be summed as unique people.

For named drugs under individual NPIs, see the Prescriber–Drug Utilization Reference. Its coverage comparison uses the same retained provider-summary source as this edition, alongside a separately revised drug-detail file. Compare prescribing datasets. For named drugs by state, use the separate Part D State Drug Utilization History. For national drug/manufacturer spending, see the national Part D spending history. This provider summary contains no named-drug-by-NPI detail or inferred NDC relationships. Compare the drug-cost and utilization datasets.

Sources and versions

Source: CMS Medicare Part D Prescribers by Provider, observation year 2024. CMS’s catalog marks the file modified August 3, 2026; ACD retained it October 26, 2026 UTC. Those dates are separate from the ACD processing revision.

The CMS methodology describes Part D coverage, NPPES demographics from the end of the subsequent year, attribution limitations and suppression. Provider summaries aggregate all applicable events, not just the drug-level rows remaining after redaction.

The preparation record documents the retained source and validation. Same-source processing improvements are included; new source editions may be sold separately. No automatic refresh is promised. Original government data are free; ACD sells preparation, documentation, validation and delivery.

Example checked October 26, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.