Compare rehabilitation facilities and patient groups in Python

Add facility stays and patient-group payments to a rehabilitation roster using CCNs and CMGs.

Compare a rehabilitation group across facilities

You have a roster of inpatient rehabilitation facilities and want to compare service volume and Medicare payments for a particular patient group. This example connects facility summaries to case-mix group (CMG) detail for fiscal 2024: October 2023–September 2024.

The optional input.csv selects three genuine North Carolina facility CMS Certification Numbers (CCNs) and stroke CMG 0106. The same selections appear in the roster list in the Python code below. No facility or payment observations are invented.

Download the three sample CSVs into your working folder. facilities.csv contains the selected facilities’ complete summaries; facility_groups.csv contains all their published group records; facility_coverage.csv supplies their group-coverage status. Every sample column and value comes unchanged from the purchased files.

The full $29 reference includes 1,165 facilities, 11,032 facility/CMG records and separate geographic benchmarks across eight CSV tables. Review the full product and coverage.

Code example

Run this code in a notebook cell, IPython or a script beside the three CSV files. It uses Python’s standard library. Facility summaries are indexed by fiscal year and CCN; group records add CMG to that key.

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

# Real facility/CMG selections, also supplied in example_input.csv.
roster = [
    {"facility_ccn": "340047", "cmg_code": "0106"},
    {"facility_ccn": "340061", "cmg_code": "0106"},
    {"facility_ccn": "340069", "cmg_code": "0106"},
]


def compare_facilities(roster, directory=".", fiscal_year="2024"):
    directory = Path(directory)
    def index(filename, keys):
        result = {}
        with (directory / filename).open(encoding="utf-8", newline="") as f:
            for row in csv.DictReader(f):
                if row["fiscal_year"] != fiscal_year:
                    continue
                key = tuple(row[k] for k in keys)
                if key in result:
                    raise ValueError(f"Duplicate key in {filename}: {key}")
                result[key] = row
        return result
    facilities = index("facilities.csv", ["facility_ccn"])
    groups = index("facility_groups.csv", ["facility_ccn", "cmg_code"])
    coverage = index("facility_coverage.csv", ["facility_ccn"])
    results = []
    for item in roster:
        ccn, code = item["facility_ccn"], item["cmg_code"]
        facility, group = facilities.get((ccn,)), groups.get((ccn, code))
        results.append({
            "facility_ccn": ccn, "cmg_code": code,
            "facility_name": facility["facility_name"] if facility else "Not in facility file",
            "facility_stays": facility["stays"] if facility else "",
            "facility_stays_status": facility["stays_status"] if facility else "not_in_file",
            "group_description": group["group_description"] if group else "",
            "group_stays": group["stays"] if group else "",
            "group_average_payment": group["average_payment_per_stay"] if group else "",
            "group_status": group["average_payment_per_stay_status"] if group else "not_in_public_group_file",
            "published_group_rows": coverage.get((ccn,), {}).get("published_group_rows", ""),
        })
    return results


results = compare_facilities(roster)
for row in results:
    payment = (f"${Decimal(row['group_average_payment']):,.0f}"
               if row["group_status"] == "reported" else row["group_status"])
    stays = row["facility_stays"] if row["facility_stays_status"] == "reported" else row["facility_stays_status"]
    print(f"{row['facility_ccn']} | {row['facility_name']} | facility stays: {stays} | "
          f"CMG {row['cmg_code']} stays: {row['group_stays'] or 'unavailable'} | "
          f"average Medicare payment/stay: {payment}")

Replace roster with your own selections or records read from a CSV. Keep identifiers as strings so CMG 0106 retains its leading zero. Pass a different directory to compare_facilities if needed.

Analysis of the output

340047 | North Carolina Baptist Hospital | facility stays: 152 | CMG 0106 stays: 11 | average Medicare payment/stay: $38,693
340061 | Unc Hospitals | facility stays: 278 | CMG 0106 stays: 20 | average Medicare payment/stay: $41,071
340069 | Wakemed | facility stays: 572 | CMG 0106 stays: 40 | average Medicare payment/stay: $36,819

UNC Hospitals reports 278 rehabilitation stays overall, including 20 in CMG 0106. Its reported average Medicare payment for that group is $41,071 per stay. The corresponding group averages are $38,693 at North Carolina Baptist Hospital and $36,819 at WakeMed. These are published group averages, not ratios calculated from the facilities’ total payments.

The join adds useful patient-group context to a facility roster. It also keeps total facility stays separate from the narrower group count. Comparing the same CMG narrows the comparison, but does not make payment differences a measure of quality, efficiency or the causal effect of choosing a facility. Beneficiary characteristics, geographic payment adjustments and other payment factors still differ.

If a requested group has no public row, the code reports not_in_public_group_file instead of inventing a zero. The coverage file distinguishes a missing selected group from a facility with no published group detail at all. Suppression applies independently to detailed tables, so group sums need not reproduce facility totals.

Using the full dataset

Extract the purchased ZIP and replace the three sample CSVs with the full files. The code runs unchanged. The full facility table has 156 fields, including beneficiary characteristics, diagnosis shares, therapy minutes and explicit numeric-availability statuses. The group table has 45 fields; 957 facilities have published detail and 208 summary facilities do not.

Keep clinical_category_day_pct separate from individual CMG measures. This is the share of covered days in a broader clinical category, repeated on its CMG rows; summing those repeated percentages would overstate the share. Therapy minutes from IRF-PAI assessments cover the first two weeks of care, not complete stay therapy totals.

The other files supply 53 summary benchmarks, 2,824 geographic/group benchmarks, original-row accounting, field definitions and source editions. Use published benchmarks rather than trying to reconstruct suppressed totals. Beneficiaries can overlap across providers and groups.

For another setting, the skilled nursing reference provides its own stays and therapy measures. Their assessment periods and patient populations differ. The hospital and care-facility selection page explains the available products and their separate purchases.

Sources and versions

Source: CMS Medicare Post-Acute Care Utilization, Inpatient Rehabilitation Facility by Geography and Provider, and by Geography, Provider and Service. Both FY2024 distributions were modified August 11, 2026 and retained by ACD October 28, 2026 UTC. The fiscal observation window follows the CSV and methodology; generic catalog calendar dates are retained separately.

These are paid Original Medicare fee-for-service observations, not complete Medicare Advantage encounters, all-payer activity or current facility coverage. Allowed amounts include beneficiary and third-party responsibility; Medicare payment is a separate field. Dollars are nominal historical amounts. Geographic payment standardization is not adjustment for patient severity.

ACD’s documentation flags misaligned identity-field definitions in the detailed dictionary and a depression variable with conflicting bipolar prose. Original definitions remain beside reviewed notes. Read the source and preparation record. Original government data are free; ACD sells preparation, validation, documentation and delivery. Same-source processing improvements are included; automatic refresh is not promised.

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