NDC to ATC in Python

Add ATC classifications to a drug-data table using the NDC → ATC Crosswalk. This guide includes free product samples, a Python example, and instructions for using the full dataset.

Example scenario

Suppose you have a drug inventory with an NDC and a quantity for each record, and you want to add ATC classifications. We created an eight-row inventory so you can try that join without supplying your own data.

The example uses three inputs:

  • Example inventory: available as input.csv and included as the inventory = [...] list in the Python code below. The rows are identical, so downloading this CSV is optional. Its line IDs and quantities are made up. We selected real NDCs with and without classifications, then added an 11-digit format example, a placeholder code and a blank value to demonstrate how the join handles different inputs.
  • crosswalk.csv: real classification records selected unchanged from the paid product. This supplies the ATC fields to add to the inventory.
  • lookup-status.csv: real lookup records selected unchanged from the product’s companion table. This explains the source-lookup result for NDCs without a classification.

What the crosswalk provides

The NDC → ATC Crosswalk connects FDA drug package codes to ATC classifications through RxNorm. Its CSV contains the NDC, resolved RxCUI, product name, and ATC codes and labels at levels 1–4. These fields let you group matched records by drug class in an inventory or utilization analysis.

The prepared crosswalk supplies these relationships in a file you can join to your own data. The example below uses ATC level 4 and retains your original rows, including records without a classification.

Download the product samples

Save the two reference CSVs in your notebook’s working folder. They have the same columns as the complete files. The example inventory is already included in the code below.

The paid download includes both complete reference tables. When using your own data, replace the example inventory with your records.

These samples demonstrate the file structure and join behavior. They do not estimate the proportion of your data that will match. View full coverage, fields and pricing →

Code example

Run the code below in one Jupyter cell or an IPython session. It reads the two sample CSVs, joins the inventory to the classification and lookup tables, and prints the result. It uses Python’s standard library and can also run as a Python script.

The file paths are relative to your working folder. To check that folder, run from pathlib import Path; print(Path.cwd()). You can also use full paths in the two open(...) calls.

Python 3.10+ · Jupyter, IPython or a script
import csv
import re
from collections import defaultdict

# Download these two SAMPLE reference files from the guide into your working folder.
with open("crosswalk.csv", newline="", encoding="utf-8-sig") as f:
    crosswalk = list(csv.DictReader(f))
with open("lookup-status.csv", newline="", encoding="utf-8-sig") as f:
    lookup = list(csv.DictReader(f))

# Example customer inventory (defined here, not in either reference CSV).
# Line IDs and quantities are fictional; NDCs include real codes and input cases.
# NDCs are text. Keep leading zeros and hyphens exactly as supplied.
inventory = [
    {"line_id": "L1", "ndc": "0002-0152-01", "units": 10},
    {"line_id": "L2", "ndc": "0002-0152-01", "units": 5},
    {"line_id": "L3", "ndc": "0002-0213-01", "units": 8},
    {"line_id": "L4", "ndc": "0002-0013-03", "units": 6},
    {"line_id": "L5", "ndc": "0002-1717-28", "units": 7},
    {"line_id": "L6", "ndc": "00002015201", "units": 3},
    {"line_id": "L7", "ndc": "99999-9999-99", "units": 4},
    {"line_id": "L8", "ndc": "", "units": 2},
]

classes = defaultdict(list)
seen = set()
for row in crosswalk:
    key = (row["ndc_code"], row["atc4_code"])
    if key in seen:
        raise ValueError(f"Duplicate crosswalk relationship: {key}")
    seen.add(key)
    classes[row["ndc_code"]].append(row)

statuses = {row["ndc_code"]: row["status"] for row in lookup}
if len(statuses) != len(lookup):
    raise ValueError("The lookup file contains duplicate NDCs.")
if {code for code, status in statuses.items() if status == "classified"} != set(classes):
    raise ValueError("Use crosswalk and lookup files from the same sample or release.")

package_ndc = r"(?:[0-9]{4}-[0-9]{4}-[0-9]{2}|[0-9]{5}-[0-9]{3}-[0-9]{2}|[0-9]{5}-[0-9]{4}-[0-9]{1,2})"
results = []
for row in inventory:
    code = row["ndc"]
    valid_format = re.fullmatch(package_ndc, code) is not None
    matches = classes.get(code, []) if valid_format else []
    if not code:
        outcome = "missing_input"
    elif not valid_format:
        outcome = "unsupported_input_format"
    elif matches:
        outcome = "matched" if len(matches) == 1 else "matched_multiple"
    else:
        outcome = statuses.get(code, "not_in_lookup_table")
    for match in matches or [{}]:
        results.append({**row, "atc4_code": match.get("atc4_code", ""),
                        "match_status": outcome, "match_count": len(matches)})

print(f"{'Line':<5} {'NDC':<15} {'Units':>5} {'ATC-4':<7} Outcome")
for row in results:
    print(f"{row['line_id']:<5} {row['ndc'] or '(empty)':<15} {row['units']:>5} "
          f"{row['atc4_code'] or '-':<7} {row['match_status']}")

Analysis of the output

Line  NDC             Units ATC-4   Outcome
L1    0002-0152-01       10 A10BX   matched
L2    0002-0152-01        5 A10BX   matched
L3    0002-0213-01        8 A10AB   matched
L4    0002-0013-03        6 -       no_current_rxcui
L5    0002-1717-28        7 -       no_atc4
L6    00002015201         3 -       unsupported_input_format
L7    99999-9999-99       4 -       not_in_lookup_table
L8    (empty)             2 -       missing_input

The output retains each inventory line’s NDC and quantity and adds an ATC-4 code where a mapping is available. The Outcome column describes the result of the join. The rows are also available in the results variable for further analysis.

ATC classifications

Lines L1–L3 receive classifications from the crosswalk. The corresponding labels, included in atc4_name in the sample CSV, are:

  • A10AB — Insulins and analogues for injection, fast-acting
  • A10BX — Other blood glucose lowering drugs, excl. insulins

You can use these codes and labels to organize matched records by class. The full crosswalk also includes the broader ATC levels 1–3, allowing analysis at different levels of detail.

Lookup results

The other rows illustrate source-mapping gaps and input issues. The lookup table distinguishes these cases so you can decide which records need identifier preparation or further investigation.

no_current_rxcui · L4
The NDC appears in the FDA source directory, but the retained RxNorm Current Prescribable Content does not resolve it to a current RxCUI.
no_atc4 · L5
The NDC resolves to an RxCUI, but the direct NLM ATCPROD lookup provides no ATC-4 classification for that product.
unsupported_input_format · L6
The input is an 11-digit billing-style value. It needs identifier preparation before it can be matched to this crosswalk’s hyphenated package codes.
not_in_lookup_table · L7
This demonstration placeholder is absent from the supplied lookup file. With the complete file, this status means the NDC is absent from that release’s source universe; with a sample, it means only absence from the sample.
missing_input · L8
The input NDC is blank. Supply a code before attempting classification.

A missing classification here does not rule out a mapping in another source or historical release. The complete lookup table also identifies ambiguous RxCUIs, unsupported source formats, and missing or conflicting product names where applicable.

Validate the example result

These checks confirm that the example retains the inventory lines and quantities and produces the expected matches. Run them after the example code.

assert len(results) == len(inventory) == 8
assert [r["line_id"] for r in results] == [r["line_id"] for r in inventory]
assert sum(int(r["units"]) for r in results) == 45
assert sum(r["match_status"] == "matched" for r in results) == 3
print("All eight inventory rows kept; three matched.")

For your own data, review match_count before aggregating quantities. If an NDC has multiple classifications, the code retains each relationship and marks the rows matched_multiple. Its quantity then appears once per classification, so a total across all output rows would double count it. Choose an aggregation rule appropriate to your analysis.

Use the full crosswalk with your data

The complete release contains 162,167 NDC-to-ATC relationships and a lookup-status table covering 256,748 source NDCs. It classifies 63.2% of the FDA package codes in its source snapshot; your match rate will depend on the codes and dates in your own data.

The purchased files use the same columns as the samples. To adapt the example:

  1. Unzip your download and replace crosswalk.csv in the first open(...) call with the path to ActuallyCleanData_NDC_to_ATC_Crosswalk.csv.
  2. Replace lookup-status.csv with the path to ndc_lookup_status.csv from the same ZIP.
  3. Replace the demonstration inventory = [...] block with your own records. For a CSV containing line_id, ndc and units, use:
with open("my-inventory.csv", newline="", encoding="utf-8-sig") as f:
    inventory = list(csv.DictReader(f))

Adapt the column names and printed fields to your file. CSV values are read as text, preserving leading zeros; convert quantity fields when you need to calculate totals. Replace the example’s fixed row-count and quantity checks with checks for your input.

Keep the reference files from the same release together. The code checks duplicate relationship keys and agreement between the classified-code lists; metadata.json provides the full crosswalk’s checksum for verifying the downloaded file.

NDC → ATC Crosswalk

Complete dataset · $49

Includes the 11-column crosswalk, complete lookup-status table, field dictionary, source versions and release documentation. One-time purchase; see the update policy for source editions and included processing revisions.

View product details ↗

Buy the crosswalk · $49

Sources, versions and scope

FDA package directory
2026-10-09
RxNorm Current Prescribable Content
05-Oct-2026
NLM ATCPROD mapping source
1.2026.7
ACD source edition
2026-10-cpc-direct
ACD package prepared (UTC)
2026-10-13T13:56:09Z

Source versions describe the inputs; ACD’s processing turns those inputs into the crosswalk. The example manifest records the published package and checksums. ATCPROD’s version is not a verified WHO edition. See the release history for changes to sources and processing.

The crosswalk uses direct product membership from NLM ATCPROD, which considers ingredients, strength and dose form and aims to reflect the most common indication. It does not enumerate every indication or the classes of all related products.

RxNorm Current Prescribable Content covers active concepts; this release does not provide historical resolution. FDA directory inclusion does not establish approval. The product supplies ATC levels 1–4, without level 5 or defined daily doses, and is intended for data analysis rather than clinical decisions.

ATC classification: WHO Collaborating Centre for Drug Statistics Methodology. Mappings supplied through NLM ATCPROD. Actually Clean Data is an independent preparation service; no endorsement is implied.