Sub topic 2
A section layout that tells a story
This chapter covers how to order the sections of an EDA notebook so a reader can follow the investigation from question to conclusion. It assumes you know basic Python and pandas, have run cells in Jupyter, and know introductory statistics. The previous chapter covered framing questions. Here you turn those questions into a notebook skeleton.
Why layout matters
A notebook is a document that also runs code. Readers who open it, including you in three weeks, need to answer four things quickly:
- What question is this notebook trying to answer?
- Where does the data come from?
- What was done to the data, and in what order?
- What did the analysis find?
A pile of ad-hoc cells answers none of these. A fixed section order answers all four, because the reader learns where to look. Consistency also helps the notebook run correctly, since each section depends only on the sections above it.
The standard section order
The order below follows the dependencies between steps. You cannot audit data you have not loaded, and you should not plot data you have not cleaned.
| Section | Purpose | Typical contents |
|---|---|---|
| Title and goals | State the questions and scope | Markdown only |
| Setup | Make the run reproducible | Imports, seed, paths, options |
| Load data | Bring in raw data unchanged | `read_csv`, `df_raw` |
| First look | Learn size, types, summaries | `shape`, `info`, `describe` |
| Data quality | Find problems | Missing values, duplicates, odd values |
| Cleaning | Fix problems with explicit rules | A function returning a new DataFrame |
| Univariate analysis | One variable at a time | Histograms, counts, summaries |
| Bivariate analysis | Pairs of variables | Box plots, scatter plots, group means |
| Findings | Record what you learned | Observations, hypotheses, next steps |
| Next steps and handoff | Tell the next reader what to do | Open questions, summary |
The order is a default, not a law. If your first look shows the data is already clean, the cleaning section can be one line. If a plot reveals a quality problem, go back and add a check to the quality section. Do not add a patch cell next to the plot. Keeping each problem in its home section is what makes the notebook readable.
Start with a title cell
The first cell should be Markdown. It names the analysis, states the questions, and says what data it uses. Here is an example for an orders dataset.
# Order amounts by region
**Questions**
1. How are order amounts distributed?
2. Do amounts differ between regions?
**Data:** `data/raw/orders.csv`, one row per order.
**Out of scope:** forecasting and customer-level analysis.Listing what is out of scope matters as much as listing questions. It stops the notebook from growing into every analysis you think of along the way.
Use headings as a table of contents
Give each section a Markdown heading. Use one # heading for the title and ## for each section in the table above. Use ### for sub-steps and individual findings. Jupyter and most notebook editors build an outline from headings, which lets a reader jump straight to "Data quality".
Write headings that say something. "Cleaning" is a label. "Cleaning: drop duplicates, normalize region, remove invalid amounts" tells the reader what happens before they read any code.
Add narrative between code cells
Each section should open with one or two sentences of Markdown that say what you are about to do and why. After a result, add a sentence about what it means. You do not need to write an essay. A good ratio is a short Markdown cell for every one to three code cells.
Compare these two versions of the same step.
df_raw.isna().sum()versus a Markdown cell saying "Check which columns have missing values, because amount is used in every later plot," followed by the same code. The code is identical. Only the second version tells the reader why the check exists.
Keep each section's code small
Each code cell should do one thing. That makes failures easy to locate and results easy to cite. A section can have several cells, but it should not contain work that belongs to another section. A few rules help:
- Imports and configuration live only in the setup cell.
- Raw data is loaded once, in the load section, into
df_raw. - Cleaning produces a new variable,
df, and later sections use onlydf. - Plots and summaries do not modify the data they describe.
The second rule is the one most often broken. If a later cell reloads the CSV or reassigns df_raw, the notebook's results depend on which cells ran in which order.
A skeleton you can copy
The following cell-by-cell skeleton shows the sections as they would appear in a notebook. The code uses only the standard libraries named in the setup. It runs as written if data/raw/orders.csv exists with order_date, region, and amount columns.
# --- Setup ---
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
SEED = 42
rng = np.random.default_rng(SEED)
RAW_PATH = Path("data/raw/orders.csv")
# --- Load data ---
df_raw = pd.read_csv(RAW_PATH, parse_dates=["order_date"])
# --- First look ---
print(df_raw.shape)
df_raw.info()
# --- Cleaning ---
def clean_orders(df):
out = df.drop_duplicates().copy()
out["region"] = out["region"].str.strip().str.lower()
out = out[out["amount"].notna() & (out["amount"] >= 0)]
return out
df = clean_orders(df_raw)
print(f"rows kept: {len(df)} of {len(df_raw)}")
# --- Univariate analysis ---
ax = df["amount"].plot.hist(bins=30)
ax.set_title("Order amount distribution")
ax.set_xlabel("Amount")
ax.set_ylabel("Number of orders")
plt.show()In a real notebook each comment marker becomes a Markdown heading and each block is split across several cells. The comments here only show where the section boundaries fall.
Common layout errors
- Analysis before setup. Importing a library halfway down the notebook hides a dependency. A reader who runs from the top may hit a
NameError. - Cleaning scattered through plots. If you fix a value in the middle of the bivariate section, earlier plots show different data than later ones. Move every fix into the cleaning function and re-run.
- Findings only in your head. Insights stay with the author unless they are written in the notebook. The findings section, covered in a later chapter, exists for this.
- Very long notebooks. If a notebook passes about 40 cells, consider splitting it. One notebook for cleaning and one for exploration is a common division.
- Headings that change style. Mixing "Step 3", "Plot of amounts", and "More stuff" makes the outline useless. Pick a pattern and keep it.
Check the layout by reading only the headings
A quick test of your layout is to read only the headings, top to bottom. They should read like an outline of the investigation: goals, setup, load, first look, quality, cleaning, one variable, two variables, findings. If you cannot tell what the notebook found from the headings and Markdown cells alone, add narrative until you can.
Exercise
You are halfway through the bivariate section when a box plot shows a region spelled "North " with a trailing space, which splits one region into two boxes. Where should the fix go, and why?
Show answer
Add the fix to the cleaning function, for example by stripping whitespace from region, and re-run the notebook from the cleaning section down. Fixing it in the bivariate section would leave the univariate plots and counts using unclean data, and the notebook's results would depend on cell order. If the problem was not caught earlier, also add a check for it to the data quality section, such as listing the unique region values.
Exercise
Why should the notebook load the CSV into df_raw once and have all later sections use df, the cleaned copy, instead of reloading and editing the file in several places?
Show answer
A single load keeps the original data untouched and available for comparison, and a single cleaning step means every later section sees the same data. Reloading or editing in several places makes the results depend on which cells ran and in what order.