Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Best Practices

Structuring a Notebook

Organize notebooks so others can read and rerun them: a clear title and purpose, setup cell, headings, small focused cells, narrative Markdown and a closing summary.

Two notebooks can contain the same code and still be very different to read. One starts with a title, explains the question, loads data in one tidy place, walks through the analysis in short steps and ends with a conclusion. The other is a pile of cells in the order the author thought of them, with df2, df_final and df_final_v3 scattered through 300 cells. Notebooks are meant to tell a story, and structure is what lets the story survive.

This lesson gives a template and the habits behind it. Everything here is writing and layout advice. The runnable cells analyze notebook structure as data: they build an outline from headings and flag structural smells.

A template that works

  1. Title and purpose. One Markdown cell: what question does this answer, for whom, and when was it last run?
  2. Setup. Imports, constants (seed, paths, parameters), configuration. One cell, or a few small ones.
  3. Load. Read data and show its shape. Keep raw data untouched.
  4. Clean. Fix types, missing values, outliers; record what you changed and why.
  5. Explore or analyze. One question per section, each with a heading and a sentence of explanation.
  6. Results. The final tables and charts the reader came for.
  7. Conclusions and next steps. What did you learn, what are the limits.
  8. Appendix. Long or optional material, kept at the end.
flowchart TD
  A["Title and purpose"] --> B["Setup"]
  B --> C["Load"]
  C --> D["Clean"]
  D --> E["Analyze"]
  E --> F["Results"]
  F --> G["Conclusions"]

Top to bottom means the notebook runs cleanly in order (see hidden state).

Use headings as a table of contents

Use Markdown headings consistently: # once for the title, ## for sections, ### for steps. JupyterLab's Table of Contents panel and exported HTML build a navigable outline from them, and collapsing a heading hides everything beneath it. Notebooks without headings are impossible to skim.

Python Build an outline from Markdown headings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output is an indented outline, which is what the Table of Contents panel shows. If a notebook produces a flat or empty outline, it needs headings.

Keep cells small and single-purpose

A cell should do one thing you can name: "load the file", "plot revenue by month", "define the cleaning function". Reasons:

  • A short cell is quick to re-run and to debug.
  • The execution count and the output belong to a clear step.
  • Diffs and reviews are readable.

Avoid cells with 100 lines. A long cell is a function in disguise; give it a name and a docstring. Equally, avoid splitting one thought into twenty one-liners with no explanation.

Write the narrative

Markdown cells are what make a notebook more than a script. Good ones:

  • state the question before the code ("Does tenure predict churn?"),
  • say what the reader should notice after a result ("Note the spike in March"),
  • explain choices that could look arbitrary (why you dropped rows, why this threshold),
  • are short. Two to five sentences beat a wall of text.

Put the conclusion in text, not only in a chart: "Churn is highest in the first three months" can be copied into a report; a chart cannot be searched.

Name things well

Use descriptive variable names (orders_raw, orders_clean) instead of df, df2. Avoid reusing one name for different things across cells. Name your notebook files for what they do and order them when they form a pipeline: 01-load.ipynb, 02-clean.ipynb, 03-model.ipynb. Do not use Untitled12.ipynb or final_FINAL.ipynb; Git is your history.

Put the important code first, helpers last (or in a module)

Readers want the story first. If a helper function takes 40 lines and is not interesting, move it to a module and import it (see moving code into modules), or place it in an appendix section the main text links to.

Control the output

Long outputs bury the story. Use df.head() rather than printing a data frame; df.sample(5, random_state=0) is better than head() when row order is meaningful. Set display options once in setup (pd.options.display.max_rows = 20). Collapse noisy cells (the blue bar at the left collapses a cell's output, and you can collapse input in JupyterLab) and clear outputs from cells whose output is not part of the story.

For charts: give each a title, labeled axes and units, and avoid generating the same plot six times with different colors. If a figure is important, save it to a file (fig.savefig("figures/churn-by-tenure.png", dpi=150)) so it can be used elsewhere.

Check your notebook for smells

Structure can be measured crudely. This stand-in checks a list of cells for common problems: no title, no headings, very long cells, and many unexplained code cells in a row.

Python A structure checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rules of thumb like these are crude, but a script can flag them for every notebook in a repository, which is how teams keep standards without long meetings.

A short review before sharing

  • Restart the kernel and run all cells; does it finish without errors?
  • Is the first cell a title that says what the notebook is for?
  • Do the headings give a sensible outline?
  • Are all imports at the top and paths and seeds defined once?
  • Are there unused cells, leftover experiments or commented-out code? Delete them.
  • Do outputs fit on a screen, without 5,000-row printouts?
  • Are secrets and personal data absent (see notebook security)?

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should the first cell of a notebook usually be?

    A title and purpose tells the reader what the notebook answers before any code.
  2. 2. Why use consistent Markdown headings?

    Tools such as the Table of Contents panel and HTML export use headings to build navigation.
  3. 3. Which is a good cell size?

    Single-purpose cells are easy to run, debug and review.
  4. 4. What is a better habit than naming files final_v3.ipynb?

    Version control records history, so file names can describe purpose.

Summary

  • Follow a template: title, setup, load, clean, analyze, results, conclusions.
  • Use headings for an outline, small single-purpose cells, and short narrative Markdown.
  • Name variables and files descriptively; keep outputs short and figures labeled.
  • Review structure before sharing, ideally with a script.

Next: Moving Code into Modules