Data exports · For Python usersUpdated December 1, 2026

Export EDC data to Python (pandas) without losing codes, labels or markers

A practical guide for data managers and statisticians who analyse trial data in Jupyter or plain Python scripts. Read the wide CSV with the right dtypes, turn dictionary codes into categoricals, merge forms on participant and visit, and read SDTM XPT files with labels intact.

  • Copy-ready pandas code
  • Dictionary to categorical dtype
  • SDTM XPT with pyreadstat

Free sandbox · No credit card · 21 CFR Part 11 compliant

  • ISO 27001 certified
  • 21 CFR Part 11 compliant
  • GDPR compliant
  • EU and US data hosting
  • HIPAA compliant
  • ICH GCP E6(R3) compliant
DEMO-101: from export to notebook
  1. Export Raw data (CSV)

    Metadata header unticked, Site 003 filter

  2. Download data dictionary

    Names, labels, types, valid values

  3. read_csv with dtype=str

    Markers kept as text

  4. 4

    Apply dictionary

    Codes to categorical labels

  5. 5

    Merge forms on SUBJID + VISIT

    validate="one_to_one"

  6. 6

    Save analysis file + hash

    Ties output to the export log entry

Demo study. File and column names are examples.

Python export in five points

  • Untick "Include metadata header" before you export a CSV for pandas. Header lines start with #, and if you leave them in, read_csv takes the first one as the column row. The snippet below detects and skips them if you forget.
  • Read everything as text first. pandas turns the string NA into a missing value by default, which would merge a "not available" marker with a blank. Use dtype=str and keep_default_na=False, then convert columns on purpose.
  • Use the data dictionary to build categoricals. Raw data carries codes; the dictionary carries labels and valid values. Mapping one to the other in code gives you ordered categories and catches unexpected codes.
  • Merge forms on participant and visit with validate. pandas can check that a join is one-to-one, which finds duplicate submissions before they double your rows.
  • For SDTM, read the XPT files. pandas.read_sas reads SAS transport files; pyreadstat also returns the variable labels. See the CDISC SDTM export page for what the package contains.

Choosing the export

Which Capture export to feed into pandas

Capture lists its exports under Reports > Data & Exports > Export Data, as described in the export study data help article. For Python work, four of them matter. Raw data gives variable names and coded values with SUBJID, SITEID and VISIT columns, one row per submission: this is your analysis input. Decoded data has question text as headers and labels instead of codes: good for a quick look, awkward for code. Codes + labels puts the code and label side by side with the not-done markers ND, NA and VND, plus a dictionary file. Data dictionary lists every variable with its label, type and valid values.

If you want everything in one go, the Complete package (ZIP) holds raw and decoded data, the dictionary, the audit trail, and site and enrolment files. Python reads the ZIP directly with the standard zipfile module, so a script can open the archive you downloaded without unpacking it by hand. Data exports can be filtered by site and by completeness rather than by date, so for an interim snapshot use an interim lock by cutoff and export after it, or filter the frame in pandas.

If your team also works in R, SAS, SPSS or Stata, the R, SAS, SPSS and Stata export guide has the equivalent snippets. This page goes deeper on Python only.

Step 1

Read the raw CSV with pandas, safely

Each row is one line of Python. The file name is a placeholder: Capture names exports after the study, the report and the date.

What it doesCode
Importimport pandas as pd, itertools, hashlib
Count metadata header lines (if you left them in)with open(path, encoding="utf-8-sig") as f: n_meta = sum(1 for _ in itertools.takewhile(lambda line: line.startswith("#"), f))
Read everything as text, blanks as missingraw = pd.read_csv(path, skiprows=n_meta, dtype=str, keep_default_na=False, na_values=[""], encoding="utf-8-sig")
Check the shape against the Export Previewprint(raw.shape); print(raw[["SUBJID", "SITEID", "VISIT"]].head())
Find the not-done markers per columnmarkers = raw.isin(["ND", "NA", "VND"]).sum(); print(markers[markers > 0])
Excel instead of CSV (needs openpyxl)sheets = pd.read_excel(xlsx_path, sheet_name=None, dtype=str)

Why not comment="#"? It would also cut any value that contains a # character mid-line, such as a free-text note. Counting the leading lines is safer. utf-8-sig removes a byte-order mark if one is present and is harmless if not.

Step 2

Convert numbers, dates and markers on purpose

Once the frame is text, decide column by column what each value means. For a numeric field, keep a flag before you convert: first set markers = ["ND", "NA", "VND"] and raw["SYSBP_ND"] = raw["SYSBP"].eq("ND") to record that the measurement was not done. Then flag the markers with is_marker = raw["SYSBP"].isin(markers), blank them with cleaned = raw["SYSBP"].mask(is_marker) and convert with raw["SYSBP_NUM"] = pd.to_numeric(cleaned, errors="coerce") to get a float column. If anything other than a marker turns into NaN at this step, you have found a data issue worth a query rather than a silent loss.

Capture exports dates as text in YYYY-MM-DD form, so parse them with an explicit format: pd.to_datetime(raw["VSDAT"], format="%Y-%m-%d", errors="coerce"). Values that do not match the format become NaT. Count them and look at the originals before you move on, because the statistical analysis plan, not pandas, should decide what happens to an incomplete or unexpected date. The statistical analysis plan guide covers where that rule belongs.

Participant IDs follow the site numbering, for example 001-0042 at Site 001. Keep SUBJID and SITEID as strings: reading them as numbers drops leading zeros and breaks joins with other files.

Step 3

Apply the data dictionary as categorical dtypes

The dictionary lists variable names, labels, types and valid values for every form. Check its headers and the layout of the valid values in a sandbox export; the column names below (VARIABLE, LABEL, CODE, DECODE) are placeholders to rename.

What it doesCode
Read the dictionary as textdd = pd.read_csv(dict_path, dtype=str, keep_default_na=False)
Build one code-to-label map per variablemaps = {var: dict(zip(g["CODE"], g["DECODE"])) for var, g in dd.groupby("VARIABLE")}
Find codes the dictionary does not knowbad = {v: set(raw[v].dropna()) - set(m) - {"ND", "NA", "VND"} for v, m in maps.items() if v in raw}
Turn a coded column into an ordered categoricalraw["AESEV_LBL"] = pd.Categorical(raw["AESEV"].map(maps["AESEV"]), categories=list(maps["AESEV"].values()), ordered=True)
Keep variable labels for tables and plotslabels = dict(zip(dd["VARIABLE"], dd["LABEL"]))

An ordered categorical sorts severity as mild, moderate, severe instead of alphabetically, and value_counts() shows zero counts for categories nobody used, which is what a summary table usually needs.

Run these snippets on a real export today

Build a two-form study in the free sandbox, enter a few sample participants, export Raw data and the dictionary, and test your notebook before the first real participant. No credit card.

Start free

Step 4

Merge forms and switch between wide and long

A raw export is wide: one row per submission, one column per field. Analyses usually need several forms side by side, for example vital signs and the dosing form for the same visit. Merge on the keys and ask pandas to check the relationship: vs.merge(ex, on=["SUBJID", "VISIT"], how="left", validate="one_to_one"). If a participant has two submissions of the same form at a visit, pandas raises a MergeError instead of quietly duplicating rows. Demographics merge many-to-one: visits.merge(dm, on="SUBJID", how="left", validate="many_to_one").

Long format is easier for plotting, mixed models and anything grouped by parameter. pd.melt turns the wide vital signs frame into one row per measurement: long = vs.melt(id_vars=["SUBJID", "SITEID", "VISIT"], value_vars=["SYSBP", "DIABP", "PULSE"], var_name="PARAM", value_name="AVAL"). Going back is a pivot: long.pivot(index=["SUBJID", "VISIT"], columns="PARAM", values="AVAL").reset_index(). If pivot complains about duplicate entries, that is the same duplicate-submission issue, and it should be resolved in the data, not by switching to pivot_table with an aggregate.

Repeating rows such as concomitant medications or lab panels are already one row per entry in their own table. Count rows per participant before joining them to visit-level data, so a many-to-many join cannot inflate your denominators. The repeating forms guide explains how those tables are built.

DEMO-101 join plan (validate argument)
Keysvalidate
Vital signs + dosingSUBJID, VISITone_to_one
Visits + demographicsSUBJIDmany_to_one
Visits + site listSITEIDmany_to_one
Con meds + visitsSUBJID, VISITmany_to_one
Adverse events + demographicsSUBJIDmany_to_one
Demo plan. A MergeError at this step is a data finding, not a coding problem.

Step 5

Read SDTM XPT datasets in Python

The CDISC SDTM report downloads a ZIP with one SAS transport (XPT) file per domain plus define.xml. Two libraries read them.

What it doesCode
pandas, no extra installdm = pd.read_sas("dm.xpt", format="xport", encoding="utf-8")
pyreadstat, with labels (pip install pyreadstat)import pyreadstat; dm, meta = pyreadstat.read_xport("dm.xpt")
Variable labels from pyreadstatmeta.column_names_to_labels["AGE"]
Read every domain in a foldersdtm = {p.stem.upper(): pd.read_sas(p, format="xport", encoding="utf-8") for p in pathlib.Path("sdtm").glob("*.xpt")}
Join a supplemental qualifier backsupp = sdtm["SUPPDM"].pivot(index="USUBJID", columns="QNAM", values="QVAL").reset_index()

pandas reads SAS transport version 5 files. If a file will not open, try pyreadstat, and check one file from a sandbox export before you build a pipeline around it. The last row needs import pathlib.

Reproducibility

Notebooks that an auditor can follow

A notebook that worked once is not an analysis record. Treat the import as code that will run at every cut-off. Keep the read-in, the dictionary mapping and the merges in a module or a single top cell, pin the pandas and pyreadstat versions in a requirements file, and restart the kernel and run all cells before you save any output. Jupyter will happily show results from cells that ran in a different order.

Tie every output to the export that produced it. Capture records every download in the export log with the user, time, export, format, row count and whether it was blinded. On your side, store the SHA-256 of the input file next to the results: hashlib.sha256(open(path, "rb").read()).hexdigest(). Anyone can then check that the file in your analysis folder is the file the export log describes.

Blinding carries into Python. Treatment arms appear only in an unblinded export, which needs an unblinded role, a justification and a password, and is marked in the log. Keep blinded and unblinded notebooks in separate folders with separate access. If an external analyst only needs de-identified data, restricted access for outside reviewers gives them a download without names, contact details or dates, with arms as coded labels.

In Capture

Exports built for code, not just for spreadsheets

Every eCRF in Capture carries an OID and an SDTM domain, and every field a variable name, so the column names in your pandas frame come from the study build rather than from free-text headers. Edit checks raise an automatic query when a value breaks a range rule, so fewer impossible values reach your script. Exports come as Excel or CSV in wide format with an automatic data dictionary, raw and decoded versions, a by-site filter, and SDTM datasets as SAS XPT with Define-XML. A Data Manager can freeze and lock data before the analysis file is cut.

  • Variable names set in the form builder.
  • Codes, labels and markers in separate reports.
  • Every download listed in the export log.
How SDTM export works
DEMO-101 export log (illustrative)

Exports this month

7

Blinded

6

Rows, last Raw data export

1,312

Raw data CSV4/7
Data dictionary2/7
CDISC SDTM ZIP1/7
Demo numbers. Real log entries show user, time, export, format, row count and blinding.

Workflow

From sandbox to final analysis in Python

  1. 1

    Agree variable names before go-live

    Review the form build against the analysis plan: every endpoint component a coded field, units fixed, not done kept separate from missing. Renaming a variable later breaks every script.

  2. 2

    Export from the sandbox

    Enter sample data, export Raw data with the metadata header unticked, plus the dictionary. Write the read-in module against those files.

  3. 3

    Add assertions

    Check row counts against the Export Preview, unknown codes against the dictionary, and join cardinality with validate. Fail loudly.

  4. 4

    Re-run at each cut-off

    Lock, export, hash the file, run the notebook top to bottom, and file the outputs with the export log entry.

  5. 5

    Move to SDTM when you need it

    For submission work, read the XPT datasets with pyreadstat so variable labels travel with the data.

FAQ

Questions teams ask before they switch

Something not covered here? Ask us directly.

How do I export EDC data to Python?

Export the Raw data report as CSV with the metadata header unticked, download the data dictionary, and read the file with pandas.read_csv using dtype=str and keep_default_na=False. Then convert numbers and dates on purpose and map codes to labels from the dictionary.

Why does pandas turn NA into a missing value?

By default read_csv treats strings such as NA, N/A and NaN as missing. In a trial export NA can be a marker meaning not available, so switch the defaults off with keep_default_na=False and declare only empty cells as missing with na_values=[""].

What is the metadata header and how do I skip it?

An optional block at the top of a Capture export with the study name, export date and filters. Each line starts with #. Untick Include metadata header before exporting for a statistics package, or count the leading # lines and pass that number to skiprows.

Can pandas read SDTM XPT files?

Yes. pandas.read_sas(path, format="xport") reads SAS transport version 5 files. pyreadstat.read_xport also returns metadata, including variable labels.

Should I use the raw or the decoded export in Python?

Raw for analysis, because codes are stable and the dictionary gives the labels. Decoded files use question text as headers, which makes column names long and fragile in code.

Does Capture have a Python API?

This page does not describe one. The route into Python is the CSV, Excel or SDTM XPT export, which you can test end to end in the free sandbox.

Test your pandas pipeline on a real export

Free sandbox, no credit card. Build the study, enter sample data and test every export before go-live.

Start free