5 Working with Python in Quarto
A hospital quality analyst must report waiting times each month. The report contains a table, a figure and a paragraph describing the results. If a corrected observation changes the mean, all three should change together. Python supplies the computational instructions; Quarto connects those instructions to the publication. This chapter develops that workflow using synthetic records, not actual patient information.
5.1 Learning objectives
Readers will configure a Python kernel, distinguish executable cells from listings, validate and summarize data, construct accessible graphics, insert dynamic results, parameterize reports, and manage computational dependencies.
5.2 From Python source to publication
Python is a programming language, while Jupyter provides an infrastructure for executing code through kernels. A kernel is a running process associated with a particular interpreter. Quarto coordinates execution and passes the resulting content through Pandoc for conversion. An editor is not itself the interpreter: two editors may use the same Python installation, or one editor may offer several installations.
A .qmd file stores narrative and executable instructions in plain text. A notebook (.ipynb) stores cells and potentially their outputs in JSON. Quarto normally executes computational .qmd files during rendering, but notebooks normally retain saved outputs unless execution is requested. This distinction matters when a dataset has changed. A notebook can look complete while containing old results.
quarto render report.qmd
quarto render report.ipynb --executeNeither successful execution nor attractive formatting establishes that a statistical conclusion is correct. Inspect the data, assumptions and interpretation separately.
5.3 Preparing an isolated environment
Create an environment from the project root. On Windows PowerShell:
py -m venv .venv
.venv\Scripts\Activate.ps1On macOS or Linux:
python3 -m venv .venv
source .venv/bin/activateThen run these commands in the activated environment:
python -m pip install jupyter pandas numpy matplotlib scipy
python -m ipykernel install --user --name quarto-textbook --display-name "Python (Quarto textbook)"
quarto check jupyter
jupyter kernelspec listActivation adjusts the terminal’s search path. Using python -m pip associates package installation with the interpreter invoked by python. Registering a kernel gives Jupyter a named way to launch that interpreter. If PowerShell prevents activation, use the environment’s Python executable directly rather than weakening organizational security settings. A kernel registration is local to a machine; collaborators must recreate it.
The examples use the following standalone document metadata. Replace the kernel name if your environment uses a different registered kernel.
---
title: "Clinic waiting-time report"
format: html
jupyter: quarto-textbook
---To diagnose interpreter mismatches, execute import sys; print(sys.executable) in a document cell and compare the result with the interpreter used to install packages. A missing module often means that installation and execution occurred in different environments.
5.4 Executable cells and their options
A fence containing {python} marks executable code. A fence containing only python displays a listing. The latter is appropriate for examples of deliberately incorrect code, installation commands, and textbook excerpts that readers should run independently.
```{python}
#| label: calculate-wait
wait = [12, 18, 15, 25, 10]
print(sum(wait) / len(wait))
```
The expected output is 16.0. Cells share the kernel’s state within a document. Define variables before referring to them. An interactive notebook may retain objects from earlier experiments, so restart the kernel and run all cells before trusting the result.
| Option | Purpose |
|---|---|
echo: false |
Hide source code while retaining results |
eval: false |
Display code without running it |
include: false |
Execute setup without displaying code or output |
warning: false |
Suppress warnings only after investigation |
error: false |
Stop on execution errors |
fig-cap |
Supply a figure caption |
label |
Identify a cell or cross-referenceable result |
Hiding code does not protect confidential data. Inspect the HTML, supporting files, notebooks and repository before distributing a report. Use synthetic or appropriately authorized data for teaching.
5.5 Worked investigation: clinic waiting times
The file data/clinic-ch04.csv contains eleven synthetic appointments. The research question is descriptive: how do observed waiting times differ between clinics A and B? The unit is an appointment, and waiting time is measured in minutes. One appointment in clinic B has no recorded waiting time. It must not be interpreted as zero.
5.5.1 Import and validation
Run the standalone examples from examples/ch05/. Their relative path points to the shared data directory. If you move a document, update the path or preserve the directory structure.
import pandas as pd
import numpy as np
df = pd.read_csv('../../data/clinic-ch04.csv')
assert df['id'].is_unique
assert df['clinic'].isin(['A', 'B']).all()
assert df['wait_min'].dropna().ge(0).all()
assert np.isfinite(df['wait_min'].dropna()).all()
print(df.isna().sum())The assertions represent explicit expectations about the data. They are not a substitute for a data dictionary: for example, a nonnegative waiting time may still be implausible if the source records seconds instead of minutes. Missing values should be investigated in the context of data collection. A failed assertion should trigger investigation rather than automatic deletion of records.
5.5.2 Constructing summaries
summary = df.groupby('clinic')['wait_min'].agg(
total='size', observed='count', mean='mean', median='median', sd='std'
)
summary['missing'] = summary['total'] - summary['observed']
print(summary.round(2))size counts all rows in a group; count counts nonmissing values. pandas computes the mean and median from available values by default. The sample standard deviation uses a denominator of n minus one. These conventions must be made explicit when reporting results. Rounding the displayed table should not change the underlying numbers used in subsequent calculations.
| Clinic | Total | Observed | Missing | Mean | Median |
|---|---|---|---|---|---|
| A | 5 | 5 | 0 | 16 | 15 |
| B | 6 | 5 | 1 | 12 | 11 |
The observed difference is four minutes. This is a descriptive comparison of a small synthetic dataset, not evidence that clinic assignment causes longer waits. Appointment complexity, staffing and missingness could influence a real comparison.
5.5.3 Numerical arrays and denominators
observed = df['wait_min'].dropna().to_numpy()
print(np.mean(observed))
print(np.std(observed, ddof=1))
print(np.mean(observed >= 15))The last expression computes the fraction of observed waits of at least 15 minutes. Boolean values are treated as zeros and ones. Dropping missing values before constructing the comparison is essential: otherwise a missing value may be treated as a false comparison and incorrectly included in the denominator. The pooled mean is 14 minutes, and the observed fraction at least 15 minutes is 0.4.
5.6 Tables and graphics
A DataFrame displayed as the final expression of a Jupyter cell can produce a rich table. For portable Markdown output, use to_markdown() with the optional tabulate package, or explicitly construct a Markdown table. The example below uses IPython’s Markdown display to avoid adding that dependency.
from IPython.display import Markdown, display
rows = ['| Clinic | Observed | Mean (min) |', '|---|---:|---:|']
for clinic, row in summary.iterrows():
rows.append(f'| {clinic} | {int(row.observed)} | {row["mean"]:.1f} |')
display(Markdown('\n'.join(rows)))Use tables for precise values and graphics for patterns. With five observations per group, a dot plot preserves individual measurements that a bar chart of means would conceal.
```{python}
#| label: fig-python-waits
#| fig-cap: "Observed waiting times by clinic."
#| fig-alt: "Clinic A has observations from 10 to 25 minutes; clinic B from 8 to 17 minutes."
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 2.8))
for i, clinic in enumerate(['A', 'B']):
values = df.loc[df.clinic.eq(clinic), 'wait_min'].dropna()
ax.scatter(values, [i] * len(values), label=clinic)
ax.set(yticks=[0, 1], yticklabels=['A', 'B'], xlabel='Waiting time (minutes)', ylabel='Clinic')
fig.tight_layout()
plt.show()
```
Reference the figure in the narrative using @fig-python-waits. The label must be unique within the publication. The caption explains what is shown, while alternative text communicates the relevant visual information to readers who cannot see the image. Avoid relying on color alone to distinguish groups.
5.7 Dynamic narrative
Quarto supports inline Python expressions in computational documents. For example, after defining mean_a = summary.loc['A', 'mean'], write the following source in a paragraph:
The observed mean in clinic A was `{python} f'{mean_a:.1f}'` minutes.This removes the need to retype a number after a data correction. It does not automate the scientific interpretation: a sentence saying that A is larger than B may become false after new data arrive. Either revise the prose after rendering or generate conditional wording from a reviewed rule. Always inspect the final publication.
5.8 Parameterized reports
A parameter is a value supplied to a document to control its analysis. For Jupyter, define default parameters in a cell tagged parameters:
```{python}
#| tags: [parameters]
clinic = 'A'
```
In a subsequent cell, validate the parameter and select records:
if clinic not in ['A', 'B']:
raise ValueError('Clinic must be A or B')
selected = df.loc[df.clinic.eq(clinic), 'wait_min'].dropna()
if selected.empty:
raise ValueError('No observed waiting times')
print(f'Clinic {clinic}: {selected.mean():.1f} minutes')From the example directory, render the report with an alternative parameter:
quarto render parameterized.qmd -P clinic:B --output clinic-b.htmlUse distinct output names to avoid overwriting earlier reports. Parameterization is useful for repeated reporting, but comparisons remain meaningful only when the same measurement definitions and inclusion criteria apply across groups.
5.9 Caching, freezing and dependency management
Caching reuses computational outputs to reduce repeated work. Jupyter caching requires the jupyter-cache package. Enable it using execute: {cache: true} in YAML. A cache may not detect changes to external data files, so refresh it explicitly when inputs change.
python -m pip install jupyter-cache
quarto render clinic-python.qmd --cache-refreshProject-level freezing is different: freeze: auto can reuse prior computations during a full project render when source files have not changed. A changed CSV may not trigger execution. Before publication, deliberately rerun affected documents and inspect the results. Do not use cached output to conceal a broken computational environment.
Record dependencies in a dedicated environment. The following commands capture installed Python package versions and recreate them in a new environment:
python -m pip freeze > requirements-lock.txt
python -m pip install -r requirements-lock.txtA package list is not a complete record of the operating system, Python version, system libraries or Quarto version. Record those separately. Use a clean environment to test the installation instructions. Never commit the .venv directory or credentials to a public repository.
Randomized computations require additional care. Use rng = np.random.default_rng(2026) and draw values from that generator when demonstrating simulations. A fixed seed supports repeatability within a compatible software environment but does not guarantee identical results across every version or platform.
5.10 Guided practice
5.10.1 Activity 1: Diagnose the environment
Create a standalone document that prints the interpreter path, Python version and pandas version. Render it, compare the interpreter with the terminal’s Python, and explain any discrepancy. Record the kernel name in the README.
5.10.2 Activity 2: Investigate missingness
Calculate missing counts and observed means by clinic. In a copy of the CSV, replace the missing value with 30 minutes to simulate a correction. Predict the new clinic B mean before rendering. Compare the new result with your prediction and explain why zero imputation would answer a different question.
5.10.3 Activity 3: Improve a figure
Recreate the dot plot with a descriptive title or caption, clear units and alternative text. Add a vertical reference line at 15 minutes and explain whether it represents a policy target or merely an illustrative threshold. Do not imply that it is an actual clinical standard.
5.10.4 Activity 4: Generate two reports
Render the parameterized document for A and B with distinct filenames. Attempt an invalid clinic parameter and verify that the report fails rather than silently generating an empty result. Explain why explicit validation matters in automated reporting.
5.11 Troubleshooting
| Symptom | Diagnostic action |
|---|---|
| Quarto command not found | Verify installation and terminal PATH |
| Kernel unavailable | Inspect jupyter kernelspec list and register the intended environment |
| ModuleNotFoundError | Compare sys.executable with the package installation interpreter |
| FileNotFoundError | Check the working directory and relative data path |
| NameError | Check cell order; restart and rerun all cells |
| Stale numerical output | Refresh cache and verify external inputs |
| Blank plot | Check data and call plt.show() |
| PDF failure after successful HTML | Investigate the TeX installation and format-specific features |
Start with the first error, not the last message in a long traceback. Reproduce the failure in a minimal document, change one factor at a time, and record the successful correction. A minimal reproducible example is often more useful than a screenshot of a long error message.
5.12 A deeper look at Python objects and vectorized computation
A list is an ordered collection, whereas a NumPy array provides numerical operations over its elements. Multiplying a list by two repeats its contents; multiplying a numerical array by two scales each measurement. This distinction is important when converting units. Consider waiting times measured in minutes. Converting to seconds requires multiplication by sixty, not repetition of sixty copies of the records.
x = np.array([12, 18, 15, 25, 10], dtype=float)
seconds = 60 * x
centered = x - x.mean()
print(seconds)
print(centered)The centered observations sum to zero up to floating-point precision. Their squared deviations sum to 138. Dividing by four gives the sample variance, 34.5 square minutes. The standard deviation is the square root of that variance and is expressed in minutes. The population-style denominator used by NumPy by default is not the sample denominator used by pandas. Specify ddof=1 when estimating sample variability.
assert np.isclose(centered.sum(), 0)
assert np.isclose(np.sum(centered**2), 138)
assert np.isclose(np.var(x, ddof=1), 34.5)Use np.isclose rather than exact equality for calculations involving floating-point arithmetic. Choose tolerances appropriate to the units and the consequences of numerical error. An assertion is a test of a stated expectation, not proof that all other aspects of the analysis are correct.
5.13 Building a reusable validation and analysis pipeline
A useful research report separates data acquisition, validation, transformation, analysis and presentation. This organization allows a collaborator to test individual components without rendering the entire publication. In the supplied extended laboratory, the function validate checks identifiers, group membership and plausible numeric values. The function analyze produces the audit table and inference results. The Quarto document imports these functions rather than duplicating their logic.
def validate(df):
if df.id.isna().any() or not df.id.is_unique:
raise ValueError('Invalid appointment identifiers')
if not df.clinic.isin(['A', 'B']).all():
raise ValueError('Invalid clinic')
x = df.wait_min.dropna()
if not np.isfinite(x).all() or (x < 0).any():
raise ValueError('Invalid waiting time')
return dfMissing identifiers differ from missing outcomes: without an identifier, the analyst may not be able to establish whether a row is a duplicate. A missing outcome can remain in an audit table while being excluded from a particular numerical calculation. A validation function should not silently discard either type of record. For a real clinical dataset, additional checks would be specified by the protocol, including measurement units, eligible dates and repeated visits by the same patient.
5.13.1 Laboratory: test a failure deliberately
Create a copy of the original DataFrame and change one waiting time to a negative number. Call the validation function on the copy and confirm that it raises a ValueError. Repeat with a duplicated identifier and an unrecognized clinic. Preserve the original data. Record the expected and actual outcomes of each test. If the invalid data pass validation, revise the validation rule, not the expected result.
5.13.2 Transforming data without losing provenance
clean = df.assign(wait_seconds=df.wait_min * 60)
observed = clean.dropna(subset=['wait_min']).copy()
observed['long_wait'] = observed.wait_min >= 15The assign method returns a new DataFrame. Retaining the original minutes column makes the unit conversion auditable. The explicit copy after filtering makes the intended ownership of the derived table clear. A threshold indicator should be constructed only after the denominator has been established. The original dataset has eleven records, ten observed waits and four observed waits of at least fifteen minutes. The reported proportion is therefore 4/10, not 4/11. If the scientific question concerns all eleven appointments, the unknown outcome must be acknowledged. Without further assumptions the fraction meeting the criterion among all appointments lies between 4/11 and 5/11.
5.14 Statistical inference with SciPy
The descriptive difference in clinic means is minus four minutes. To illustrate statistical uncertainty, assume independent observations within and between groups and a sampling design for which a two-sample mean comparison is appropriate. With only five observed values per group, the normality assumption and possible selection effects deserve particular attention. The following analysis is a teaching example, not a clinical recommendation.
The Welch standard error is
\[SE=\sqrt{s_A^2/n_A+s_B^2/n_B}.\]
Here the sample variances are 34.5 and 12.5, so the standard error is \(\sqrt{9.4}\approx3.066\). The test statistic is the estimated difference divided by its standard error. Welch’s method uses an approximate degrees-of-freedom calculation rather than pooling the variances.
from scipy import stats
a, b = [df.loc[df.clinic.eq(g), 'wait_min'].dropna().to_numpy()
for g in ['A', 'B']]
fit = stats.ttest_ind(b, a, equal_var=False)
ci = fit.confidence_interval(confidence_level=0.95)
print(fit.statistic, fit.df, fit.pvalue)
print(ci)The order of arguments matters: b, a estimates B minus A. Reversing the arguments changes the signs of the estimate, statistic and interval endpoints, but not the two-sided p-value. The estimate is -4.00 minutes, the statistic is approximately -1.305, the degrees of freedom are 6.562, and the two-sided p-value is 0.235896. The interval is approximately (-11.35, 3.35) minutes. The interval includes zero, but also includes potentially meaningful differences in either direction. It is incorrect to conclude that the clinics are equivalent. A formal equivalence analysis would require a justified margin and a suitable design.
5.14.1 Connecting the comparison to a regression model
A binary indicator can represent clinic membership. Define \(z=0\) for A and \(z=1\) for B, and write \(E(Y\mid z)=\beta_0+\beta_1z\). The intercept estimates the mean in A, while the coefficient estimates the difference B minus A.
import statsmodels.api as sm
complete = df.dropna(subset=['wait_min']).copy()
X = sm.add_constant(complete.clinic.eq('B').astype(int).rename('clinic_B'))
model = sm.OLS(complete.wait_min, X).fit()
print(model.params)The coefficients are 16 and -4. The default OLS standard errors assume constant error variance and need not match Welch’s test. Matching coefficients do not imply matching inference. This example prepares readers for regression-based reports in which additional predictors may be introduced, but adding predictors to a tiny dataset does not solve confounding or establish causation.
5.15 Simulation as a reproducible mathematical investigation
Suppose independent hypothetical waiting times follow a normal distribution with mean 20 and standard deviation 6 minutes. A sample mean based on 25 observations has theoretical standard error 1.2 minutes. The normal model permits negative values, so it is an illustrative mathematical model rather than a universal model for waiting times. A simulation can investigate how closely repeated samples follow the theoretical result.
rng = np.random.default_rng(2026)
means = rng.normal(20, 6, size=(5000, 25)).mean(axis=1)
print(means.mean(), means.std(ddof=1))The array has 5000 rows and 25 columns. Each row represents one hypothetical sample. The argument axis=1 averages across columns within each row; averaging along axis zero instead would produce 25 means of 5000 observations and answer a different question. In the supplied run the simulated mean is 20.013717 and the simulated standard deviation is 1.192859. The differences from 20 and 1.2 reflect Monte Carlo variability.
The histogram uses density scaling so the theoretical density and histogram have compatible units. A count histogram cannot be directly compared with a probability density curve without rescaling. Increase the number of simulated samples to investigate Monte Carlo stability; increase the number of observations per sample to investigate sampling variability. These are two distinct experimental controls.
5.16 Publication-quality graphics and tables
A figure should answer a specific question. For a small sample, show individual values. For a simulation with thousands of observations, a histogram is more useful. A confidence interval plot communicates the estimated effect and uncertainty, but should not replace the underlying sample description. In Matplotlib, construct a figure and axes explicitly, label units, remove unnecessary spines and save with an appropriate resolution.
fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.hist(means, bins=30, density=True, color='#214e70', edgecolor='white')
grid = np.linspace(15, 25, 400)
ax.plot(grid, stats.norm.pdf(grid, 20, 1.2), color='#26766a')
ax.set(xlabel='Sample mean (minutes)', ylabel='Density')
ax.spines[['top', 'right']].set_visible(False)
fig.tight_layout()
fig.savefig('sampling.png', dpi=300, facecolor='white')The figure dimensions determine the physical size at a given resolution. Increasing DPI does not fix overlapping labels or misleading axes. For print, vector formats such as PDF can preserve line and text sharpness; PNG is widely portable across web and word-processing outputs. Inspect the final rendered figure at its intended size. Use descriptive captions and alternative text, and ensure that distinctions remain understandable without color.
5.17 Extended laboratory: computational handoff
Copy examples/ch05/extended/ outside the book project. Create an isolated environment, install the requirements, register or select a Python kernel, and execute python analysis.py. Compare the results with expected-output.txt, allowing for small numerical differences across software versions. Render report.qmd and compare its inline numbers with the script output. Record the Python, Quarto and dependency versions. If the kernel is not named python3, adjust the document metadata to match the registered kernel. The script uses its own location to find the data; the report uses the document directory. Keep the files together.
5.18 Extended review and investigation exercises
- Convert the clinic A observations to seconds. Explain how the mean and variance change.
- Calculate the sample variance by hand and compare it with NumPy’s default variance.
- Explain the difference between a missing outcome and a missing identifier.
- Write a test that rejects an invalid clinic code without altering the original data.
- Derive the lower and upper bounds on the all-appointment threshold proportion.
- Reverse the arguments to Welch’s test and explain which results change.
- Explain why the default OLS standard error need not equal the Welch standard error.
- Repeat the simulation with sample size 100 and predict its standard error before running it.
- Explain why a density histogram is appropriate for overlaying a theoretical density.
- Describe how you would detect a stale inline result after correcting a CSV file.
5.19 Extended applied project: a computational quality-improvement report
Develop a portable Python analysis module and Quarto report using the synthetic clinic dataset. Include a validation function with at least three deliberate failure tests, an audit table with explicit denominators, descriptive statistics, Welch inference with limitations, a regression coefficient comparison, a simulation with two sample sizes, and accessible figures. Submit the source, data, dependency record, rendered report and reproduction instructions. A peer should reproduce the results without relying on your interactive notebook state.
| Criterion | Points |
|---|---|
| Validation and failure tests | 6 |
| Statistical accuracy and limitations | 8 |
| Simulation and mathematical explanation | 6 |
| Accessible graphics and dynamic report | 5 |
| Independent reproduction evidence | 5 |
| Total | 30 |
5.20 Chapter summary
Python provides computation, Jupyter manages execution, and Quarto integrates the resulting outputs with prose and publication structure. Reliable reports depend on explicit environments, validated data, transparent denominators, appropriate graphics and fresh execution. Parameterization reduces duplication; caching reduces computational cost but requires deliberate invalidation. Reproducibility is a property of the entire workflow, not merely a file extension.
5.21 Review exercises
- Distinguish a Python interpreter from a Jupyter kernel.
- Explain why an editor can use a different interpreter from the terminal.
- Describe the default rendering difference between
.qmdand.ipynb. - Distinguish
echo: falsefromeval: false. - Explain why
include: falseis not a privacy safeguard. - Write a command to list installed kernels.
- Explain the difference between
sizeandcountin the clinic example. - Calculate the pooled observed mean by hand.
- Calculate the fraction of observed waits at least 15 minutes.
- Explain why missing waiting times should not automatically become zeros.
- Explain why a dot plot is appropriate for this dataset.
- Write an inline expression displaying the mean to one decimal place.
- Describe how to reject an invalid clinic parameter.
- Explain why an external CSV change can require a cache refresh.
- Distinguish package version recording from complete environment documentation.
- Explain why the observed difference does not establish a causal clinic effect.
5.22 Applied project: a reproducible clinic report
Prepare a standalone Quarto report for a quality-improvement audience. Use the supplied synthetic clinic data. Include a research question, data provenance, validation checks, observed and missing counts, means and medians, a labeled figure, a dynamically computed numerical statement and a limitations paragraph. Produce two parameterized HTML reports, one per clinic, and document the environment and rendering commands. Submit the source, data, README and rendered outputs. Do not submit private records.
| Criterion | Points |
|---|---|
| Reproducible environment and instructions | 5 |
| Data validation and missingness | 5 |
| Accurate computations and dynamic narrative | 5 |
| Professional figure and accessible presentation | 5 |
| Parameterization and responsible interpretation | 5 |
| Total | 25 |
5.23 Further reading
5.24 Supplemental assessment
- Conceptual (4 points). Explain the distinction between a missing value and a zero in pandas.
- Technical (8 points). Read the supplied waits.csv, drop missing waits, calculate mean and median, then compare >15 and >=15.
- Applied (8 points). Create an executable report with an assertion that detects accidental replacement of missing waits by zero.
See the student assessment packet in the source package for submission guidance and any required datasets.
5.25 Looking ahead
Use these computational methods to produce mathematical equations, tables and figures in Chapter 6.
5.26 Interactive learning lab
Explore the activity below, then explain what changed and why.