Compare Medicare drug spending and prescription use in Python
Compare annual spending growth with prescription-fill growth using prepared CMS drug totals, with clear units and a free product sample.
Compare spending and prescription use
Suppose you are preparing a drug-market brief and want to understand why annual spending rose. Start by comparing total spending with prescription fills, then examine spending per fill. The prepared annual table lets you make those comparisons without reshaping CMS’s separate columns for every year.
This example selects Eliquis, Jardiance and Ozempic, using the exact brand-name and generic-name pairs in CMS’s data. The optional input.csv lists those three pairs; the identical portfolio list appears in the Python code below. They are analysis choices, not fictional claims or patients.
drug_years.csv below is a sample of the paid product’s main table, containing all five annual records for those three drug groups and every product column. The complete download supplies 3,625 drug groups, separate manufacturer detail, published trend measures and documentation. The sample is enough to run this guide.
Download the sample into your working folder. This guide uses the all-manufacturer drug totals. You do not need to combine them with the manufacturer table.
Code example
Copy the code into one notebook cell or a Python script. It compares 2023 with 2024 and prints the 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.
import csv
from decimal import Decimal
# Real CMS name pairs, also supplied in the guide's 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: +13.7% | +13.5% | +0.1%
Jardiance: +29.4% | +39.4% | -7.2%
Ozempic: +41.1% | +50.4% | -6.2%
Eliquis’s gross spending and prescription fills increased by similar percentages. Its spending per fill changed little. Jardiance and Ozempic had faster growth in fills than in gross spending, while their average spending per fill declined.
This is useful context for a spending brief: an increase in total spending does not, by itself, establish an increase in price. A fill can cover different quantities or durations, and the mix of strengths and forms can change. These results describe the source’s annual aggregates; they do not isolate a causal price effect.
What the dollar amounts mean
CMS reports gross spending before manufacturer rebates and other price concessions, including plan and beneficiary payments, dispensing fees and applicable tax. It is not net Medicare spending, an acquisition-cost benchmark or a patient’s copay. Claims count original prescription fills and refills, not standardized 30-day prescriptions.
The product also preserves CMS’s weighted_spending_per_dosage_unit_usd. That measure weights different strengths, forms and routes by claims; it is not simply total spending divided by total units. Use its accompanying CMS outlier flag and avoid comparing unlike dosage units.
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. Inspect drugs.csv for exact name pairs, then replace the portfolio list or load your own two-column CSV. Preserve spelling, case and any asterisk: CMS uses the asterisk to identify multiple administration routes. The prepared keys do not contain NDCs or RxCUIs.
For a manufacturer comparison, use manufacturer_years.csv and include manufacturer_name in your key. Do not add manufacturer rows to the already aggregated drug totals. Beneficiary counts also cannot be summed across drugs, manufacturers or years to obtain unique people.
drug_trends.csv and manufacturer_trends.csv retain CMS’s published weighted unit-spending change and CAGR, converted to percentages. These measure changes within the source’s year window; they are separate from the history of ACD processing revisions.
Coverage and source checks
This edition contains five-year history for groups present in CMS’s annual 2024 release. It is not an exhaustive list of every drug used in 2020–2023. CMS excludes over-the-counter records and groups with fewer than 11 claims in the latest year; older small counts may be redacted. Blank cells remain not_reported, since the source does not supply a reason for each blank.
The package flags 149 older drug-total records where CMS’s beneficiary count exceeds its claim count. Those values agree with CMS’s companion workbook and are preserved, with beneficiary_claim_check=beneficiaries_exceed_claims. Avoid beneficiary-based utilization ratios for those records. None of the 2024 observations has that particular discrepancy.
For help choosing a source, see Choosing drug-cost data: NADAC, Medicare and Medicaid.
Sources and versions
CMS Medicare Part D Spending by Drug, annual 2024 edition, with a 2020–2024 benefit-year window. CMS metadata was modified June 25, 2026; the dictionary is dated June 3, 2026. ACD prepared this package on 2026-10-20. Preliminary quarterly releases are not included.
Raw source files, lossless staging, preparation and publication have separate retained identities. Same-source improvements are included for buyers; a new source edition may be sold separately. There is no scheduled refresh commitment.
Example checked October 20, 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 NDC-level acquisition benchmarks, see the NADAC history and its Python guide. For package identity or therapeutic grouping, inspect the FDA NDC reference and NDC → ATC crosswalk. These answer different questions; this Part D file has no automatic NDC join.