Medications¶
The medications module provides tools for medication lookup, treatment identification, episode detection, and adherence calculation.
When to Use¶
Use the medications module when you need to:
- Look up NDC codes or J-codes by generic name
- Identify treatment claims for specific medications
- Categorize medications into therapeutic classes
- Identify treatment episodes and switches
- Calculate adherence metrics (PDC)
- Classify payer types
Quick Example¶
from alx_heor.database import RedshiftConnection
from alx_heor.medications import (
lookup_medications,
get_treatment_claims,
identify_treatment_episodes,
calculate_pdc,
)
conn = RedshiftConnection().connect()
# Look up C5 inhibitors by generic name
meds = lookup_medications(
conn,
schema="iqvia_pharmetrics_2024q3",
generic_names=["eculizumab", "ravulizumab"],
)
print(f"Found {len(meds.ndc_codes)} NDC codes, {len(meds.procedure_codes)} J-codes")
# Get treatment claims for cohort
df_rx = get_treatment_claims(
conn,
source="iqvia",
schema="iqvia_pharmetrics_2024q3",
patient_ids=df_cohort["pat_id"].tolist(),
generic_names=["eculizumab", "ravulizumab", "efgartigimod"],
start_year=2015,
end_year=2024,
)
# Identify treatment episodes
df_episodes = identify_treatment_episodes(
df_rx,
patient_id_col="pat_id",
date_col="from_dt",
drug_col="generic_name",
gap_days=60, # New episode if >60 day gap
)
# Calculate PDC for each episode
df_pdc = calculate_pdc(
df_episodes,
patient_id_col="pat_id",
start_col="episode_start",
end_col="episode_end",
days_supply_col="days_supply",
)
Common Patterns¶
Medication Lookup¶
# Look up by generic name
result = lookup_medications(
conn,
schema="iqvia_pharmetrics_2024q3",
generic_names=["eculizumab"],
)
# Access NDC codes and J-codes
ndc_list = result.ndc_codes # ['12345678901', '12345678902', ...]
jcode_list = result.procedure_codes # ['J1300', 'J1303', ...]
Treatment Categorization¶
from alx_heor.medications import assign_medication_category
# Define categories
categories = {
"C5_INHIBITOR": ["eculizumab", "ravulizumab"],
"FCRN_INHIBITOR": ["efgartigimod", "rozanolixizumab"],
"CHOLINESTERASE": ["pyridostigmine", "neostigmine"],
}
df_rx = assign_medication_category(
df_rx,
category_mapping=categories,
drug_col="generic_name",
output_col="drug_class",
)
Payer Classification¶
from alx_heor.medications import classify_payer_type
df_payer = classify_payer_type(
conn,
source="iqvia",
schema="iqvia_pharmetrics_2024q3",
patient_ids=df_cohort["pat_id"].tolist(),
)
# Returns: pat_id, pay_type, payer_type (COMMERCIAL, MEDICARE, MEDICAID, OTHER)
Related Modules¶
cohort- Uses medications viaMedicationCriteriaclaims- Lower-level claims accessconfig- Column mappings for NDC, procedure codes
medications ¶
Medication lookup and treatment analysis utilities for pharmacoepidemiology.
This module supports medication-focused analyses in RWE studies. In claims databases, medications are identified through two coding systems: - NDC codes: National Drug Codes for pharmacy dispensings (11-digit codes) - J-codes: Healthcare Common Procedure Codes (HCPCS) for physician-administered drugs (typically biologics, infusions, injections)
Understanding these coding systems is essential because expensive specialty drugs (like C5 inhibitors for gMG) are often administered in physician offices and appear as J-codes rather than NDC codes in pharmacy claims.
Key Concepts:
NDC codes: Identify specific drug products at the manufacturer/packager level. Format: 11 digits (5-4-2 or 4-4-2 variations). Found in pharmacy claims.
J-codes: Part of HCPCS Level II, identify drugs administered by healthcare providers (infusions, injections). Format: J + 4 digits (e.g., J1300 for eculizumab). Found in medical claims.
Treatment episodes: Contiguous periods of treatment separated by gaps. A gap > 45 days typically indicates treatment discontinuation.
PDC (Proportion of Days Covered): Standard adherence metric. PDC = (Days with medication available) / (Observation period). PDC ≥ 0.8 is considered "adherent" for chronic conditions.
Core Functions:
- lookup_medications: Find NDC/J-codes from generic drug names
- get_treatment_claims: Query claims for specific medications
- identify_treatment_episodes: Group claims into treatment episodes
- calculate_pdc: Calculate medication adherence
- classify_payer_type: Classify patients by insurance type
Typical Workflow:
- lookup_medications() - Find codes for drugs of interest
- get_treatment_claims() - Query claims with those codes
- assign_medication_category() - Label claims by drug
- identify_treatment_episodes() - Group into treatment periods
- calculate_pdc() - Measure adherence (if relevant)
Example
Analyze C5 inhibitor treatment in gMG cohort:
from alx_heor.medications import ( ... lookup_medications, ... get_treatment_claims, ... identify_treatment_episodes, ... calculate_pdc, ... ) result = lookup_medications( ... conn, ... source='iqvia', ... schema='iqvia_pharmetrics_2024q3', ... generic_names=['eculizumab', 'ravulizumab', 'efgartigimod'], ... ) print(result.summary()) Medication Lookup Summary ================================================== NDC codes found: 45 - eculizumab: 12 - ravulizumab: 18 - efgartigimod: 15 J-codes found: 3 - eculizumab: 1 - ravulizumab: 1 - efgartigimod: 1 df_rx = get_treatment_claims( ... conn, ... source='iqvia', ... schema='iqvia_pharmetrics_2024q3', ... patient_ids=df_cohort['pat_id'].tolist(), ... start_year=2015, ... end_year=2024, ... ndc_codes=result.ndc_list, ... jcodes=result.jcode_list, ... ) print(f"Treatment claims: {len(df_rx):,}") df_episodes = identify_treatment_episodes( ... df_rx, ... patient_id_col='pat_id', ... gap_days=45, ... ) print(f"Patients with treatment: {df_episodes['patient_id'].nunique():,}")
See Also
cohort.MedicationCriteria : Medication-based inclusion/exclusion criteria claims.get_claims : Query claims by diagnosis (rather than medication)
Notes
- J-codes are more reliable for identifying biologics than NDC codes
- NDC codes change frequently (new manufacturers, repackagers)
- Always verify lookup results against known drug products
- Exclude hyaluronidase formulations if studying the active drug alone
MedicationLookupResult
dataclass
¶
Result from medication lookup.
Attributes:
| Name | Type | Description |
|---|---|---|
df_ndc |
DataFrame
|
NDC codes with generic names and strengths. |
df_jcodes |
DataFrame
|
J-codes/procedure codes with descriptions. |
ndc_list |
list[str]
|
List of NDC codes for SQL IN clauses. |
jcode_list |
list[str]
|
List of J-codes for SQL IN clauses. |
Source code in alx_heor\medications\__init__.py
summary ¶
Generate human-readable summary of lookup results.
Source code in alx_heor\medications\__init__.py
TreatmentEpisode
dataclass
¶
A treatment episode for a patient.
Attributes:
| Name | Type | Description |
|---|---|---|
patient_id |
str
|
Patient identifier. |
medication |
str
|
Medication name/category. |
episode_num |
int
|
Episode number (1-indexed). |
start_date |
Timestamp
|
Episode start date. |
end_date |
Timestamp
|
Episode end date. |
num_claims |
int
|
Number of claims in episode. |
duration_days |
int
|
Duration in days. |
Source code in alx_heor\medications\__init__.py
lookup_medications ¶
lookup_medications(conn: RedshiftConnection, source: str, schema: str, generic_names: list[str], exclude_keywords: list[str] | None = None, include_jcodes_only: bool = True) -> MedicationLookupResult
Look up NDC codes and J-codes for medications by generic name.
This function searches the database's medication lookup tables (rx_lookup for NDC codes, pr_lookup for procedure/J-codes) to find all codes matching the specified generic drug names. This is essential because: - A single drug may have dozens of NDC codes (different manufacturers, strengths) - J-codes identify physician-administered drugs (biologics, infusions) - Manual code lookup is error-prone and time-consuming
The function returns both the full DataFrames (for review) and convenient lists (for SQL IN clauses).
Workflow:
- lookup_medications() <-- you are here
- get_treatment_claims() - Query claims with found codes
- assign_medication_category() - Label claims by drug
- identify_treatment_episodes() - Group into treatment periods
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
RedshiftConnection
|
Active database connection. Must be connected before calling. |
required |
source
|
str
|
Data source name: 'iqvia', 'optum', 'komodo'. |
required |
schema
|
str
|
Database schema name (e.g., 'iqvia_pharmetrics_2024q3'). |
required |
generic_names
|
list[str]
|
List of generic medication names to search. Case-insensitive. Examples: ['eculizumab', 'ravulizumab'] for C5 inhibitors. |
required |
exclude_keywords
|
list[str]
|
Keywords to exclude from results. Case-insensitive. Example: ['HYALU'] to exclude hyaluronidase co-formulations. |
None
|
include_jcodes_only
|
bool
|
If True, only include J-codes (not other HCPCS codes like C-codes). J-codes are the most reliable for drug identification. |
True
|
Returns:
| Type | Description |
|---|---|
MedicationLookupResult
|
Dataclass containing: - df_ndc: DataFrame of matching NDC codes with generic_name, strength - df_jcodes: DataFrame of matching J-codes with descriptions - ndc_list: List of NDC codes (for SQL IN clauses) - jcode_list: List of J-codes (for SQL IN clauses) - summary(): Method to print human-readable summary |
See Also
get_treatment_claims : Next step - query claims with found codes cohort.MedicationCriteria : Use medication codes in cohort criteria
Notes
- Always review df_ndc and df_jcodes to verify correct drugs were found
- NDC codes change frequently - verify against current FDA database
- Exclude hyaluronidase for biologics that have subcutaneous formulations
- J-codes are more stable than NDC codes over time
Examples:
Look up C5 inhibitors for gMG treatment analysis:
>>> result = lookup_medications(
... conn,
... source='iqvia',
... schema='iqvia_pharmetrics_2024q3',
... generic_names=['eculizumab', 'ravulizumab', 'efgartigimod'],
... )
>>> print(result.summary())
>>> print(f"Found {len(result.ndc_list)} NDC codes and {len(result.jcode_list)} J-codes")
Exclude hyaluronidase co-formulations (for pure drug analysis):
>>> result = lookup_medications(
... conn,
... source='iqvia',
... schema='iqvia_pharmetrics_2024q3',
... generic_names=['eculizumab'],
... exclude_keywords=['HYALU'], # Exclude hyaluronidase formulations
... )
Review the found codes before using:
>>> result = lookup_medications(conn, source='iqvia', ...)
>>> print(result.df_ndc[['ndc', 'generic_name', 'strength']].head(10))
>>> print(result.df_jcodes[['procedure_cd', 'procedure_desc']])
Use codes in SQL query:
>>> ndc_str = ', '.join(f"'{c}'" for c in result.ndc_list)
>>> sql = f"SELECT * FROM claims WHERE ndc IN ({ndc_str})"
Source code in alx_heor\medications\__init__.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
build_medication_sql_filter ¶
build_medication_sql_filter(ndc_codes: list[str] | None = None, jcodes: list[str] | None = None, ndc_column: str = 'ndc', proc_column: str = 'proc1') -> str
Build SQL WHERE clause for medication filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ndc_codes
|
list[str]
|
List of NDC codes to filter. |
None
|
jcodes
|
list[str]
|
List of J-codes to filter. |
None
|
ndc_column
|
str
|
Column name for NDC codes (default: 'ndc'). |
'ndc'
|
proc_column
|
str
|
Column name for procedure codes (default: 'proc1'). |
'proc1'
|
Returns:
| Type | Description |
|---|---|
str
|
SQL WHERE clause (without 'WHERE' keyword). |
Example
sql_filter = build_medication_sql_filter( ... ndc_codes=['12345', '67890'], ... jcodes=['J1300', 'J9332'], ... ) sql = f"SELECT * FROM claims WHERE {sql_filter}"
Source code in alx_heor\medications\__init__.py
get_treatment_claims ¶
get_treatment_claims(conn: RedshiftConnection, source: str, schema: str, patient_ids: list[str], start_year: int, end_year: int, ndc_codes: list[str] | None = None, jcodes: list[str] | None = None, columns: list[str] | None = None) -> pd.DataFrame
Get treatment claims for specified patients and medications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
RedshiftConnection
|
Active database connection. |
required |
source
|
str
|
Data source name: 'iqvia', 'optum', 'komodo'. |
required |
schema
|
str
|
Database schema name. |
required |
patient_ids
|
list[str]
|
List of patient IDs. |
required |
start_year
|
int
|
Start year for claims tables. |
required |
end_year
|
int
|
End year for claims tables. |
required |
ndc_codes
|
list[str]
|
NDC codes to filter. |
None
|
jcodes
|
list[str]
|
J-codes to filter. |
None
|
columns
|
list[str]
|
Columns to select. If None, uses defaults. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Treatment claims for the specified patients and medications. |
Example
df_rx = get_treatment_claims( ... conn, source='iqvia', schema='iqvia_pharmetrics_2024q3', ... patient_ids=['P001', 'P002'], ... start_year=2020, end_year=2024, ... ndc_codes=['12345'], jcodes=['J1300'], ... )
Source code in alx_heor\medications\__init__.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
assign_medication_category ¶
assign_medication_category(df_claims: DataFrame, medication_map: dict[str, str], ndc_column: str = 'ndc', proc_column: str = 'proc1', category_column: str = 'medication') -> pd.DataFrame
Assign medication category to claims based on NDC or procedure codes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_claims
|
DataFrame
|
Claims data with NDC and/or procedure columns. |
required |
medication_map
|
dict[str, str]
|
Mapping of codes to medication names. Example: {'J1300': 'eculizumab', '12345678901': 'eculizumab'} |
required |
ndc_column
|
str
|
Column name for NDC codes. |
'ndc'
|
proc_column
|
str
|
Column name for procedure codes. |
'proc1'
|
category_column
|
str
|
Name for the new category column. |
'medication'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Claims with medication category column added. |
Example
med_map = {'J1300': 'eculizumab', 'J9332': 'efgartigimod'} df = assign_medication_category(df_claims, med_map)
Source code in alx_heor\medications\__init__.py
identify_treatment_episodes ¶
identify_treatment_episodes(df_claims: DataFrame, patient_id_col: str = 'pat_id', date_col: str = 'from_dt', medication_col: str = 'medication', gap_days: int = 45) -> pd.DataFrame
Identify treatment episodes from claims data.
A new episode starts when there's a gap > gap_days between claims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_claims
|
DataFrame
|
Claims data with patient, date, and medication columns. |
required |
patient_id_col
|
str
|
Patient ID column name. |
'pat_id'
|
date_col
|
str
|
Service date column name. |
'from_dt'
|
medication_col
|
str
|
Medication category column name. |
'medication'
|
gap_days
|
int
|
Maximum gap (days) within an episode. Default 45. |
45
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Episode summary with columns: - patient_id, medication, episode_num - start_date, end_date, num_claims, duration_days |
Example
df_episodes = identify_treatment_episodes( ... df_rx, patient_id_col='pat_id', gap_days=45, ... ) df_first = df_episodes[df_episodes['episode_num'] == 1]
Source code in alx_heor\medications\__init__.py
get_first_treatment_date ¶
get_first_treatment_date(df_claims: DataFrame, patient_id_col: str = 'pat_id', date_col: str = 'from_dt', medication_col: str | None = None) -> pd.DataFrame
Get first treatment date for each patient (optionally by medication).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_claims
|
DataFrame
|
Claims data. |
required |
patient_id_col
|
str
|
Patient ID column name. |
'pat_id'
|
date_col
|
str
|
Service date column name. |
'from_dt'
|
medication_col
|
str
|
If provided, get first date per patient per medication. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
First treatment date per patient (and medication if specified). |
Example
df_first = get_first_treatment_date(df_rx, patient_id_col='pat_id') df_cohort = df_cohort.merge(df_first, on='pat_id', how='left')
Source code in alx_heor\medications\__init__.py
calculate_pdc ¶
calculate_pdc(df_claims: DataFrame, patient_id_col: str = 'pat_id', date_col: str = 'from_dt', days_supply_col: str | None = None, observation_window: int = 365, index_date_col: str | None = None) -> pd.DataFrame
Calculate Proportion of Days Covered (PDC) for each patient.
PDC is the standard medication adherence metric in pharmacoepidemiology. It measures what proportion of the observation period a patient had medication available (based on dispensing records and days supply).
PDC = (Days with medication available) / (Observation window)
Clinical Interpretation:
- PDC ≥ 0.80 (80%): Generally considered "adherent"
- PDC 0.50-0.79: Partial adherence
- PDC < 0.50: Non-adherent
The 80% threshold is used because clinical outcomes typically improve significantly above this level for chronic conditions.
Calculation Method:
For each patient: 1. Define observation window (e.g., 365 days from first fill or index) 2. For each dispensing, mark days covered based on days_supply 3. Handle overlapping supplies (no double-counting) 4. PDC = unique covered days / observation window
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_claims
|
DataFrame
|
Treatment claims data with dates and optional days supply. Output from get_treatment_claims(). |
required |
patient_id_col
|
str
|
Patient ID column name. |
'pat_id'
|
date_col
|
str
|
Service date column name. |
'from_dt'
|
days_supply_col
|
str
|
Days supply column. If None or not in DataFrame, assumes 30-day supply per claim (common for biologics). |
None
|
observation_window
|
int
|
Number of days to observe (typically 365 for annual adherence). |
365
|
index_date_col
|
str
|
If provided, observation starts from this date column. Otherwise uses first treatment date as day 0. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per patient with columns: - patient_id: Patient identifier - pdc: Proportion of Days Covered (0.0 to 1.0) - covered_days: Number of days with medication available - observation_days: Length of observation window - observation_start: Start date of observation - observation_end: End date of observation |
See Also
get_treatment_claims : Get treatment claims for PDC calculation identify_treatment_episodes : Alternative approach for episodic treatment
Notes
- PDC handles overlapping supplies by not double-counting days
- For injectable biologics, days_supply may not be captured - assume 30
- PDC is typically calculated for chronic, maintenance medications
- Early discontinuation will result in low PDC (as intended)
Examples:
Calculate annual PDC for gMG treatment:
>>> df_pdc = calculate_pdc(
... df_rx,
... patient_id_col='pat_id',
... observation_window=365,
... )
>>> print(f"Mean PDC: {df_pdc['pdc'].mean():.2%}")
>>> print(f"Median PDC: {df_pdc['pdc'].median():.2%}")
Filter to adherent patients (PDC >= 80%):
>>> adherent = df_pdc[df_pdc['pdc'] >= 0.80]
>>> print(f"Adherent patients: {len(adherent):,} ({len(adherent)/len(df_pdc)*100:.1f}%)")
Stratify by adherence level:
>>> df_pdc['adherence_category'] = pd.cut(
... df_pdc['pdc'],
... bins=[0, 0.50, 0.80, 1.0],
... labels=['Non-adherent (<50%)', 'Partial (50-79%)', 'Adherent (≥80%)'],
... )
>>> print(df_pdc['adherence_category'].value_counts())
Calculate from index date (not first fill):
>>> df_with_index = df_rx.merge(df_cohort[['pat_id', 'index_date']], on='pat_id')
>>> df_pdc = calculate_pdc(
... df_with_index,
... index_date_col='index_date',
... observation_window=365,
... )
Source code in alx_heor\medications\__init__.py
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 | |
classify_payer_type ¶
classify_payer_type(df_enrollment: DataFrame, patient_id_col: str = 'pat_id', payer_col: str = 'pay_type', index_date_col: str | None = None, payer_mapping: dict[str, list[str]] | None = None) -> pd.DataFrame
Classify patients by payer type from enrollment data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_enrollment
|
DataFrame
|
Enrollment data with payer type column. |
required |
patient_id_col
|
str
|
Patient ID column name. |
'pat_id'
|
payer_col
|
str
|
Payer type column name. |
'pay_type'
|
index_date_col
|
str
|
If provided, uses payer at index date month. Otherwise uses most common payer. |
None
|
payer_mapping
|
dict
|
Custom mapping of payer categories to codes. Default: IQVIA mapping (C/S=Commercial, R/T/A=Medicare, M=Medicaid). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per patient with payer_type classification. |
Example
df_payer = classify_payer_type(df_enrollment) df_cohort = df_cohort.merge(df_payer, on='pat_id')