Compare Medicaid drug spending and prescription use in Python

Compare annual spending with prescription fills using prepared Medicaid drug totals, a free product sample and copyable notebook code.

Compare spending and prescription use

Suppose you are preparing a Medicaid drug-spending brief and want to understand what changed between 2023 and 2024. Compare annual reimbursement with prescription fills, then examine spending per fill. The prepared annual table supplies those measures together, without reshaping CMS’s separate columns for every year.

This example selects Eliquis, Jardiance and Ozempic, using their exact CMS brand-name and generic-name pairs. The optional input.csv lists those three pairs; the identical portfolio list appears in the Python code below. They are research selections, not invented claims or patients.

drug_years.csv below is a sample of the paid product’s main table. It contains all five annual records for those three groups and all 17 product fields. The full download supplies 4,774 drug groups, separate manufacturer history, trend tables and documentation. The sample is enough to run this guide.

Save the sample in your working folder. This example uses all-manufacturer drug totals; you do not need the manufacturer-detail table.

Code example

Copy this code into one notebook cell or a Python script. It compares 2023 with 2024 and prints three results. Missing numbers and zero starting values produce “not available” rather than a fabricated growth rate.

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

# Real CMS name pairs, also supplied in input.csv.
# Replace this list with your own exact name pairs after inspecting drugs.csv.
portfolio = [
    {"brand_name": "Eliquis", "generic_name": "Apixaban"},
    {"brand_name": "Jardiance", "generic_name": "Empagliflozin"},
    {"brand_name": "Ozempic", "generic_name": "Semaglutide"},
]

with open("drug_years.csv", newline="", encoding="utf-8-sig") as file:
    observations = {}
    for row in csv.DictReader(file):
        key = (row["brand_name"], row["generic_name"], row["year"])
        if key in observations:
            raise ValueError(f"Duplicate drug/year: {key}")
        observations[key] = row

def percent_change(before, after):
    if before == "" or after == "" or Decimal(before) == 0:
        return None
    return (Decimal(after) / Decimal(before) - 1) * 100

def display_change(value):
    return "not available" if value is None else f"{value:+.1f}%"

results = []
for drug in portfolio:
    key = (drug["brand_name"], drug["generic_name"])
    before = observations.get((*key, "2023"))
    after = observations.get((*key, "2024"))
    if before is None or after is None:
        raise ValueError(f"Name pair absent from this sample/edition: {key}")
    spending = percent_change(before["total_spending_usd"], after["total_spending_usd"])
    claims = percent_change(before["total_claims"], after["total_claims"])
    per_claim = percent_change(before["spending_per_claim_usd"], after["spending_per_claim_usd"])
    results.append({
        **drug,
        "spending_change_2023_2024": display_change(spending),
        "claims_change_2023_2024": display_change(claims),
        "spending_per_claim_change_2023_2024": display_change(per_claim),
    })

print("2023–2024 change | gross spending | prescription fills | spending per fill")
for row in results:
    print(f'{row["brand_name"]}: {row["spending_change_2023_2024"]} | '
          f'{row["claims_change_2023_2024"]} | '
          f'{row["spending_per_claim_change_2023_2024"]}')

Analysis of the output

2023–2024 change | gross spending | prescription fills | spending per fill
Eliquis: +10.3% | +4.1% | +6.0%
Jardiance: +22.3% | +18.1% | +3.6%
Ozempic: +59.0% | +55.4% | +2.3%

Eliquis’s spending grew faster than its prescription fills: 10.3% versus 4.1%, with spending per fill up 6.0%. Jardiance and Ozempic show much stronger growth in fills, alongside smaller increases in spending per fill. For Ozempic, the 59.0% spending increase accompanies a 55.4% increase in fills.

This helps distinguish changes in the amount of prescribing from changes in average spending per prescription. It does not isolate a price effect: fills can cover different quantities and durations, and the mix of strengths, forms and routes can change.

What the dollar amounts mean

CMS reports pharmacy reimbursement by Medicaid and non-Medicaid entities, including federal/state payments and dispensing fees, before Medicaid rebates. The figures are nominal dollars, not net program spending, pharmacy acquisition costs or patient copays. Claims count original fills and refills, not unique patients or standardized 30-day prescriptions.

The annual file also includes CMS’s weighted spending per dosage unit and its outlier flag. That average reflects claim weights across strengths, forms, routes and manufacturers; it is not total spending divided by total units. Review the flag before interpreting that measure.

Using the full dataset

After purchase, extract the ZIP and replace the sample drug_years.csv with the full file of the same name. The code works unchanged. Use drugs.csv to find exact name pairs, then replace the portfolio list or load your own two-column input CSV. Preserve case, punctuation and asterisks; CMS uses an asterisk for multiple administration routes. These name keys are not NDCs or RxCUIs.

Use manufacturer_years.csv for a manufacturer comparison, including manufacturer_name in the key. Do not add its rows to the drug totals: the scopes overlap. The Medicaid source does not provide beneficiary counts or state-level records.

Published and calculated changes

The trend tables keep CMS’s published weighted unit-spending changes separate from ACD calculations based on the annual values. For 2,341 drug groups, the CSV’s field labeled 2023–2024 disagrees with those annual endpoints. The companion workbook’s 2024 changes agree with its annual values, while these CSV values match the workbook’s previous-year changes. The cause is not established.

For a 2023–2024 endpoint comparison, use calculated_weighted_unit_change_2023_2024_pct, its calculation status and change_check, alongside the annual outlier flags. The original CMS value remains available. Two additional CSV/workbook conflicts lack a 2023 endpoint and remain uncomputable. The example above calculates spending, fills and spending-per-fill changes directly from annual records; it does not use the disputed source growth field.

Coverage

The five-year history covers groups present in CMS’s annual 2024 edition, not every drug used in earlier years. CMS’s methodology describes OTC exclusions and a minimum of 11 claims in the latest year. ACD retains the published cohort. Blank values remain not_reported, without an invented reason or a replacement zero.

Sources and versions

CMS Medicaid Spending by Drug, annual 2024 edition, with a 2020–2024 benefit-year window. Metadata was modified June 25, 2026; the dictionary is dated June 5, 2026. The linked methodology is in a May 2025 publisher path and has no printed date. ACD prepared this package on 2026-10-21.

Retained source files, lossless staging, preparation and publication have separate identities. Same-source processing improvements are included for buyers; later publisher editions may be sold separately. No scheduled refresh is promised.

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

For help choosing a source, see Choosing drug-cost data: NADAC, Medicare and Medicaid. It compares coverage, identifiers and the meaning of the dollar amounts.