Skip to content
mentoor

Topic 2 of 5 · 4 min read

From exploration to a reproducible script

Goal: Convert an exploratory notebook into a script that gives the same numbers on a clean run from pinned inputs.

An analysis is reproducible when someone else, or you in three months, can run it from a clean start and get the same numbers. An exploratory notebook rarely meets that bar, and AI-assisted notebooks are the worst case because dozens of cells get written, edited and re-run in any order.

Check yourself · 1 of 3

What is the quickest test that a notebook's results do not depend on hidden state?

Choose one answer

Why it matters

Notebook cells share one kernel. A number on the screen may come from a variable defined in a cell you later deleted, or from a cell run twice. Run "Restart and run all" and the result can change or fail. If you cannot reproduce your own number, you cannot defend it.

How to do it

  1. Restart and run all, now. If it fails or the numbers move, you have hidden state. Fix that before anything else.
  2. Pin the inputs. Read from a named file or a table snapshot with a date, not "whatever is in the folder" or a live table. Record the file name and a checksum or row count.
  3. Fix the randomness. Any sampling, shuffling or train/test split needs a seed: rng = np.random.default_rng(42), and pass it to each call.
  4. Record the environment. Keep a requirements.txt or lock file with package versions. A pandas upgrade can change defaults.
  5. Move logic into functions. Put loading, cleaning and aggregation in a .py module with one entry point. Keep the notebook for the story and charts, or switch to a reactive notebook such as marimo that stores plain Python and re-runs dependent cells.
  6. Ask the agent to refactor, then verify. Have it turn cells into functions, then run old and new versions and compare outputs with a test.
  7. Commit it. Code, lock file and a short README with the exact command.

Before and after

Before: a notebook where sample = df.sample(1000) runs without a seed, the input is pd.read_csv("export.csv") and a middle cell sets df = df[df.amount > 0] that you ran once and later commented out.

After:

def load(path):
    return pd.read_csv(path, parse_dates=["created_at"])

def build(path, seed=42):
    df = load(path)
    df = df[df["amount"] > 0]
    return df.sample(1000, random_state=seed)

if __name__ == "__main__":
    print(build("data/export_2026-11-30.csv")["amount"].sum())

Two runs now print the same number.

What goes wrong

  • Unordered cells. The notebook works only in the order you happened to run it.
  • Unpinned data. The input file or table changes, so last week's number cannot be rebuilt.
  • Agent rewrites that change results. A refactor quietly changes a filter. Compare outputs before and after.
  • Seeds set once. One np.random.seed early in a long notebook does not protect cells run later in a different order.

Examples

Hidden state caught by restart

A notebook shows total revenue of 84,210. After Restart and run all, the cell fails with NameError: name 'fx' is not defined. The currency-rate variable fx was defined in a cell the agent later removed, and the kernel still held the old value. The fix is to define fx in a visible cell and load it from a dated file.

Checking a refactor

old = legacy_notebook_total(df)
new = build('data/export_2026-11-30.csv')['amount'].sum()
assert abs(old - new) < 0.01, (old, new)

The agent's refactor is accepted only if this assertion passes on the same pinned file.

Key points

  • Restart the kernel and run all cells: if the numbers change or it fails, you have hidden state.
  • Pin inputs by file name and date or snapshot, and record a row count or checksum.
  • Seed every source of randomness and pass the seed explicitly to each call.
  • Move logic into functions with one entry point, and keep the notebook for charts and narrative.
  • After an agent refactors, compare its output with the original on the same pinned input.

Common mistakes

  • Trusting a number from a notebook that has never been run from a clean kernel.
  • Reading the newest file in a folder or a live table instead of a pinned snapshot.
  • Calling a random function without a seed, then wondering why results differ between runs.
  • Accepting an agent's refactor without comparing its output to the original.

Check yourself · 2 of 3

An analysis samples 1,000 rows with df.sample(1000) and the total changes on every run. What is the fix?

Choose one answer

Check yourself · 3 of 3

Which input choice makes a result easiest to rebuild later?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic