Compare Medicare Part D drug utilization across states in Python

Compare a drug’s claims growth and gross cost per standardized fill in three states using a genuine sample and copyable Python.

Compare a drug’s use across three states

You are preparing a state drug-market brief and want to compare prescription growth with gross spending. This example looks at Eliquis, with generic name Apixaban, in North Carolina, Virginia and California. It compares 2020 with 2024 and calculates the latest year’s gross cost per standardized 30-day fill.

The optional input.csv contains those three real state selections. They also appear in the selections list in the Python code below. The drug-name pair and comparison years are explicit variables; no observations are invented.

Download state_drug_years.csv into your working folder. This is a genuine subset of the paid product: all 15 annual observations for this drug in these three states, with all 37 fields retained. The complete $29 download has 539,119 state/drug/year records for the 50 states and DC, plus seven companion tables. Inspect the full coverage and fields.

Code example

The code uses Python’s standard library and runs in a notebook cell, IPython or a script. It reads the CSV one row at a time, so the same example can use the full purchased table.

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

# Genuine state and drug selections; replace these to study another market.
selections = [
    {'state_fips': '37', 'state': 'North Carolina'},
    {'state_fips': '51', 'state': 'Virginia'},
    {'state_fips': '06', 'state': 'California'},
]
drug_name, generic_name = 'Eliquis', 'Apixaban'
first_year, last_year = '2020', '2024'
data_path = Path('state_drug_years.csv')
selected_codes = {s['state_fips'] for s in selections}
observations = {}
with data_path.open(encoding='utf-8', newline='') as f:
    for row in csv.DictReader(f):
        if (row['state_fips'] in selected_codes and row['drug_name'] == drug_name
                and row['generic_name'] == generic_name):
            observations[(row['state_fips'], row['year'])] = row

results = []
for selection in selections:
    before = observations.get((selection['state_fips'], first_year))
    after = observations.get((selection['state_fips'], last_year))
    if before is None or after is None:
        results.append({**selection, 'status': 'endpoint_not_in_file'})
        print(selection['state'] + ': an endpoint is absent; do not assume zero use.')
        continue
    claims_growth = (Decimal(after['total_claims']) / Decimal(before['total_claims']) - 1) * 100
    # Cost per standardized fill is a research summary, not a pharmacy price.
    cost_per_fill = Decimal(after['total_drug_cost']) / Decimal(after['total_30day_fills'])
    result = {**selection, 'status': 'reported', 'first_year': first_year, 'last_year': last_year, 'claims_first': before['total_claims'],
              'claims_last': after['total_claims'], 'claims_growth_percent': f'{claims_growth:.1f}',
              'cost_per_30day_fill_last': f'{cost_per_fill:.2f}'}
    results.append(result)
    print(f"{selection['state']}: {int(before['total_claims']):,} → {int(after['total_claims']):,} claims "
          f"({claims_growth:+.1f}%); {last_year} cost per 30-day fill ${cost_per_fill:,.2f}")

Replace selections with your own state codes or load the same columns from a CSV. Keep FIPS codes as text: California is 06. Change first_year and last_year to compare another pair of years from 2020 through 2024. Other drugs or states require the full purchased table.

Analysis of the output

North Carolina: 600,460 → 931,280 claims (+55.1%); 2024 cost per 30-day fill $543.27
Virginia: 336,391 → 575,422 claims (+71.1%); 2024 cost per 30-day fill $541.30
California: 1,096,872 → 1,709,608 claims (+55.9%); 2024 cost per 30-day fill $542.47

North Carolina’s Eliquis/Apixaban claims rise from 600,460 to 931,280, a 55.1% increase. Virginia has the largest percentage increase of these three states, at 71.1%, while California has the largest absolute claim count. These are fills and refills under Part D, not counts of individual patients.

The 2024 gross cost per standardized 30-day fill is about $541–$543 in all three states. That ratio provides a common duration-based denominator for this comparison. It is calculated from total drug cost and standardized fills; it is not a pharmacy acquisition price, a beneficiary copay or a rebate-adjusted net price.

The geography is the prescriber’s NPPES location, not the patient’s residence. A higher state total can reflect more covered use, a larger covered population or other differences. These figures alone do not establish a prescribing rate per resident or a treatment recommendation.

Both drug_name and generic_name matter. A drug-name string can have multiple generic-name pairings across the history. An exact pair absent from either endpoint produces endpoint_not_in_file; the example does not substitute zero or infer why it is absent.

Choose national and Medicaid comparisons carefully

The package’s national_drug_years.csv contains CMS’s own national observations. Use it as a benchmark instead of summing states, particularly for nonadditive beneficiary counts. Our separate national Part D spending product adds manufacturer detail but uses a different reporting cohort. The state Medicaid product uses NDC, quarter and program rather than these drug-name groups. Neither companion is an automatic join.

Compare the available drug-cost and utilization datasets →

Using the full dataset

Extract the purchased ZIP and replace the sample with the complete state_drug_years.csv. The code runs unchanged. The key is year, geography ID, exact drug name and exact generic name. The table includes eleven numeric measures, companion reporting statuses and original CMS suppression and drug-category flags.

annual_changes.csv supplies adjacent-year differences in claims, standardized fills and gross costs. It identifies pairs with both years observed and pairs missing one endpoint. Name changes can interrupt an exact-name history; the product does not infer synonyms, package identifiers, approvals or discontinuations.

National and other-geography observations are separate tables. The remaining files document geography, coverage, source editions and every original record. Suppressed values stay blank, and beneficiary or prescriber counts must not be added as unique people across drugs or years.

Sources and versions

Source: CMS Medicare Part D Prescribers by Geography and Drug, annual observation years 2020–2024, retained by ACD October 25, 2026. Each annual file has its own observed drug roster. These are the available versions captured together, not a reconstruction of the original annual publication vintages.

The CMS methodology explains Part D coverage, prescriber geography, cost components and suppression. CMS changed the long-acting-opioid classification beginning in 2021. The package retains source documentation notes where dictionary prose differs from the actual file schema.

The preparation record distinguishes annual observations, publisher editions and ACD processing. Same-source processing improvements are included; genuinely 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 25, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.