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.
Free sandbox · No credit card · 21 CFR Part 11 compliant
Export Raw data (CSV)
Metadata header unticked, Site 003 filter
Download data dictionary
Names, labels, types, valid values
read_csv with dtype=str
Markers kept as text
Apply dictionary
Codes to categorical labels
Merge forms on SUBJID + VISIT
validate="one_to_one"
Save analysis file + hash
Ties output to the export log entry
Python export in five points
Choosing the export
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
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 does | Code |
|---|---|
| Import | import 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 missing | raw = 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 Preview | print(raw.shape); print(raw[["SUBJID", "SITEID", "VISIT"]].head()) |
| Find the not-done markers per column | markers = 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
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
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 does | Code |
|---|---|
| Read the dictionary as text | dd = pd.read_csv(dict_path, dtype=str, keep_default_na=False) |
| Build one code-to-label map per variable | maps = {var: dict(zip(g["CODE"], g["DECODE"])) for var, g in dd.groupby("VARIABLE")} |
| Find codes the dictionary does not know | bad = {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 categorical | raw["AESEV_LBL"] = pd.Categorical(raw["AESEV"].map(maps["AESEV"]), categories=list(maps["AESEV"].values()), ordered=True) |
| Keep variable labels for tables and plots | labels = 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.
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.
Step 4
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.
| Keys | validate | |
|---|---|---|
| Vital signs + dosing | SUBJID, VISIT | one_to_one |
| Visits + demographics | SUBJID | many_to_one |
| Visits + site list | SITEID | many_to_one |
| Con meds + visits | SUBJID, VISIT | many_to_one |
| Adverse events + demographics | SUBJID | many_to_one |
Step 5
The CDISC SDTM report downloads a ZIP with one SAS transport (XPT) file per domain plus define.xml. Two libraries read them.
| What it does | Code |
|---|---|
| pandas, no extra install | dm = 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 pyreadstat | meta.column_names_to_labels["AGE"] |
| Read every domain in a folder | sdtm = {p.stem.upper(): pd.read_sas(p, format="xport", encoding="utf-8") for p in pathlib.Path("sdtm").glob("*.xpt")} |
| Join a supplemental qualifier back | supp = 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
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
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.
Exports this month
7
Blinded
6
Rows, last Raw data export
1,312
Workflow
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.
Enter sample data, export Raw data with the metadata header unticked, plus the dictionary. Write the read-in module against those files.
Check row counts against the Export Preview, unknown codes against the dictionary, and join cardinality with validate. Fail loudly.
Lock, export, hash the file, run the notebook top to bottom, and file the outputs with the export log entry.
For submission work, read the XPT datasets with pyreadstat so variable labels travel with the data.
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.
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=[""].
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.
Yes. pandas.read_sas(path, format="xport") reads SAS transport version 5 files. pyreadstat.read_xport also returns metadata, including variable labels.
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.
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.
Keep exploring
Export to R, SAS, SPSS and Stata
The same exports in other tools.
CDISC SDTM export
SAS XPT datasets with Define-XML.
Data dictionary and codebook generator
What a good dictionary contains.
EDC for biostatisticians
Role page for the analysis team.
Export study data (help)
Every report and option, step by step.
Free sandbox, no credit card. Build the study, enter sample data and test every export before go-live.