Sub topic 3
The setup cell: imports, paths, and seeds
This chapter covers the first code cell of an EDA notebook. It assumes you know basic Python, can work with pandas DataFrames, have run cells in Jupyter, and know introductory statistics. By the end you should be able to write a setup cell that makes a notebook behave the same way on another machine, or on the same machine next month.
Why one setup cell
Notebooks hide configuration. A path typed into cell 14, a random seed set in cell 9, and an import added in cell 31 all work while you are exploring. They fail when someone else opens the notebook, or when you restart the kernel and run the cells in order.
The fix is a single setup cell near the top that holds everything the rest of the notebook depends on:
- the libraries it imports
- the paths it reads from and writes to
- the random seed
- display options
- a record of library versions
Later cells then contain analysis and nothing else. A reader who wants to know where the data comes from looks in one place.
A baseline setup cell
This is the cell used throughout the tutorial:
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")
pd.set_option("display.max_columns", 50)Each part of it is deliberate.
Imports
Group imports in the usual order: standard library first, then third-party packages, each group separated by a blank line and sorted alphabetically. The ordering makes it easy to see what the notebook needs.
Use the community aliases pd, np, and plt. Readers recognize them immediately.
Avoid from module import *. It hides where names come from, and a later import can silently replace a name you already defined.
Import everything in this cell, even libraries you only need later. If a package is missing, the notebook then fails at the top and not halfway through an analysis.
Paths
Define each path once, as a constant in capital letters, using pathlib.Path. Building paths from Path objects avoids problems with separators on different operating systems. You can also build related paths from one root:
DATA_DIR = Path("data")
RAW_PATH = DATA_DIR / "raw" / "orders.csv"
PROCESSED_DIR = DATA_DIR / "processed"
FIGURES_DIR = Path("reports") / "figures"Paths are relative to the notebook's working directory. Jupyter usually sets this to the folder containing the notebook, which is not always the project root. If the notebook lives in notebooks/, the path data/raw/orders.csv points to the wrong place. Choose a convention and state it in a markdown cell, for example "run this notebook from the project root". Alternatively, define the root explicitly:
PROJECT_ROOT = Path.cwd().parent # notebook lives in notebooks/
RAW_PATH = PROJECT_ROOT / "data" / "raw" / "orders.csv"Do not use absolute paths such as /Users/maria/projects/.... They work only on one machine.
Seeds
Some operations are random: sampling rows, splitting data, jittering points on a plot, bootstrapping a confidence interval. Without a fixed seed, each run gives slightly different numbers, and a finding like "the sample mean is 41.2" cannot be checked later.
NumPy's current recommendation is to create a Generator with np.random.default_rng(seed) and call methods on it. The older global style, np.random.seed(42), still works but affects hidden global state, which makes it harder to reason about.
A generator keeps state
A generator remembers how many numbers it has produced. Calling it again continues the sequence:
import numpy as np
rng = np.random.default_rng(42)
first = rng.integers(0, 100, size=3)
second = rng.integers(0, 100, size=3)
print(first, second) # two different triples
rng_again = np.random.default_rng(42)
print(rng_again.integers(0, 100, size=3)) # same values as `first`This has a practical consequence. If you set the seed in the setup cell and then re-run an analysis cell three times without restarting, the second and third runs draw different numbers than the first. The notebook looks reproducible, but only a full restart reproduces it.
Two ways to reduce this problem:
- Pass the seed directly to functions that accept one. For pandas sampling, write
df.sample(n=500, random_state=SEED). The result then depends only on the data and the seed, not on how many times a cell has run. - Create a fresh generator inside the cell that needs randomness:
rng = np.random.default_rng(SEED). The cell then gives the same result whenever it runs.
The first option is usually simpler for EDA. Use the shared rng for work where you do not mind the result depending on cell order, and check your findings after a restart (see the chapter on restarting and running all cells).
Other libraries have their own seeds. The standard library's random.seed(SEED) covers random. Machine learning libraries such as scikit-learn take a random_state argument. Setting a NumPy seed does not set any of these. If a library accepts a seed argument, pass SEED explicitly.
Recording versions
The same code can give different results under different library versions. A default argument changes, a function is removed, or a plot gets a different style. Print the versions you are using so a reader can compare against theirs:
import platform
print("python ", platform.python_version())
print("numpy ", np.__version__)
print("pandas ", pd.__version__)
print("matplotlib", plt.matplotlib.__version__)Do this once, in the setup cell or in a cell directly after it. Printing versions only documents the environment. It does not recreate it. For that, pin the versions in a requirements.txt or environment.yml file stored with the notebook. The printed output tells a reader which file to trust if the two disagree.
Display options
Display options change how results look. They do not change the data. A common example is pd.set_option("display.max_columns", 50), which stops pandas from hiding middle columns with ... in wide tables.
Keep these settings few and put them in the setup cell. Be cautious with options that change numeric formatting, for example display.float_format. A rounded display can make two different values look equal, which matters when you audit data quality later.
What belongs in the setup cell
| Belongs in the setup cell | Belongs elsewhere |
|---|---|
| Imports | Loading the data (a separate section) |
| Path and parameter constants | Cleaning rules |
| Seed and random generator | Plots and tables |
| Display options | Any result you want to discuss |
| Version printout | Experiments that might fail |
A setup cell should run in well under a second and should not fail unless the environment is wrong. Loading a large file in this cell makes every restart slow and mixes configuration with analysis.
Guarding against a wrong environment
A short check at the end of the setup cell turns a confusing error later into a clear one now:
if not RAW_PATH.exists():
raise FileNotFoundError(
f"Expected data at {RAW_PATH.resolve()}. "
"Run the notebook from the project root."
)The resolve() call prints the full path Python actually tried, which is usually what you need to diagnose a working-directory mistake.
Common errors
FileNotFoundErroron a path that looks right. The working directory is different from what you assumed. PrintPath.cwd()to check.- Results change after a re-run. A shared generator advanced, or a library with its own seed was left unseeded. Pass
random_state=SEEDor recreate the generator. - A name behaves oddly. A star import or an assignment in a later cell replaced something imported in the setup cell. Check for reused names such as
np,df, orplt. - The notebook works only on your machine. There is an absolute path, or an unpinned library version. Replace the path and add a requirements file.
Exercise
A colleague's notebook sets rng = np.random.default_rng(42) in the setup cell. A later cell calls rng.choice(df.index, size=200, replace=False) to draw a sample. When they run that cell twice in a row, they get different samples. Why does this happen, and give two ways to make the sample stable.
Show answer
The generator keeps state, so the second call continues the sequence and returns different values. One fix is to create a fresh generator in that cell, rng = np.random.default_rng(SEED), before drawing the sample. Another is to use df.sample(n=200, random_state=SEED), which depends only on the data and the seed. A full kernel restart also reproduces the first result, but it is not a fix for the cell itself.
Exercise
Your setup cell contains RAW_PATH = Path("/home/dev/projects/shop/data/raw/orders.csv"). Rewrite it so it works for other people, and add a check that fails early with a useful message.
Show answer
Use a relative path built from a root, for example RAW_PATH = Path("data") / "raw" / "orders.csv", and state that the notebook runs from the project root. Then add if not RAW_PATH.exists(): raise FileNotFoundError(f"Expected data at {RAW_PATH.resolve()}"). The check shows the full path Python tried.