Sub topic 3
The setup cell: imports, paths, and seeds
This chapter assumes you can run cells in Jupyter, know basic pandas, and have seen import statements and f-strings. It covers the first code cell of an EDA notebook. That cell holds everything the rest of the notebook needs to run, so no configuration is hidden further down.
Why one setup cell
Imports, file locations, and random seeds are easy to scatter across a notebook. An import in cell 14 works only because you ran it earlier, and a path edited in cell 30 changes what cell 6 reads. Putting all of this in one cell near the top gives a reader, and your future self, one place to check.
The cell
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)The cell has four parts.
- Imports. Standard library first, then third-party packages, each group in alphabetical order. This is the usual Python convention, and it makes a missing import easy to spot.
- Seed.
SEEDis a named constant, so the value appears once.rngis a NumPyGenerator. Pass it to anything random instead of relying on global state. - Path.
RAW_PATHis apathlib.Path, which handles separators on every operating system and supports methods such as.exists(). - Display options.
pd.set_optionchanges how pandas prints. It does not change your data.
Seeds only help if you use them
Setting a seed does nothing until random code actually draws from it. Each of these needs its own wiring:
| Source of randomness | How to make it repeatable |
|---|---|
| NumPy | Draw from `rng`, for example `rng.choice(...)` |
| pandas sampling | `df.sample(n=100, random_state=SEED)` |
| Python's `random` module | `random.seed(SEED)` |
| Libraries such as scikit-learn | Pass `random_state=SEED` |
Paths and the working directory
A relative path like data/raw/orders.csv is resolved against the notebook's working directory. That directory is often the notebook's own folder, but it depends on how Jupyter was started. If the notebook lives in notebooks/, the path above fails. A cheap guard makes the failure obvious:
if not RAW_PATH.exists():
raise FileNotFoundError(f"Expected data at {RAW_PATH.resolve()}")The resolve() call prints the full path pandas would have tried, which is usually enough to see the mistake.
Recording versions
Results can change between library versions, for example in default arguments or in how a function handles missing values. Print the versions you used so the output records them:
import sys
print("python", sys.version.split()[0])
print("numpy ", np.__version__)
print("pandas", pd.__version__)For a project that other people will run, also pin versions in a requirements.txt or lock file. The printed line only tells a reader what you had.
Common mistakes
- Adding imports in later cells "just for now" and never moving them up.
- Changing
RAW_PATHin the middle of the notebook, so earlier cells and later cells read different files. - Setting a seed but sampling with an unseeded call.
- Putting slow work, such as loading the full dataset, in the setup cell. It should run in well under a second.
Exercise
Your notebook sets SEED = 42 in the setup cell. Later you run df.sample(100) and get different rows each time you restart and run all. What is wrong, and how do you fix it?
Show answer
df.sample(100) is not given any seed, so it draws from fresh randomness. The setup cell's SEED is never used by it. Fix it with df.sample(100, random_state=SEED). Alternatively, pass rng where the library accepts a generator.