Skip to main content

Data analysis · Beginner · 18 min

Explore a dataset in JupyterLab without making a mess

By Padding · Updated 18 Nov 2026
Python 3.15.2 · JupyterLab 4.6.6 · uv 0.13 (checked on python:3.15-slim)

You will set up JupyterLab 4.6 in a uv project, explore a small price dataset in a notebook that gives the same answer every time it runs top to bottom, and commit it to Git with its outputs stripped.

On this page

A notebook is a good place to poke at data: you run a line, look at the result, and decide what to try next. It is also an easy place to fool yourself. A notebook remembers everything you have run, in the order you ran it, not the order the cells sit on the page. After an hour of editing and rerunning, the numbers on screen can depend on code that no longer exists.

This tutorial sets up JupyterLab so that does not happen to you. You install it inside a uv project, so the notebook always uses that project's packages. You explore a small file of weekly maize prices from three Kenyan markets (made-up figures for practice), see out-of-order execution go wrong on purpose, and build habits that keep the notebook honest: restart and run everything, load data at the top, put reusable code in a .py file, run the notebook without a browser, and strip outputs before you commit.

You will work in ~/notebook-demo and delete it at the end.

Step 1 · Create a project and install JupyterLab

Make the project folder and add the packages. pandas is a normal dependency, because the analysis needs it. JupyterLab and the tools around it go in the development group, because they help you work but are not part of the analysis itself:

Bash
mkdir -p ~/notebook-demo
cd ~/notebook-demo
uv init --no-package
uv add "pandas>=3.1,<3.2"
uv add --dev "jupyterlab>=4.6,<4.7" "ipykernel>=7.4,<7.5" "nbconvert>=7.17,<7.18" "nbstripout>=0.9,<0.10"

Each range allows patch releases and nothing newer, so an upgrade cannot change behaviour under you. uv writes the ranges to pyproject.toml, the exact versions it picked to uv.lock, and installs everything into .venv inside the folder. Nothing is installed globally, so a second project can use a different JupyterLab without a clash. If Git is installed, uv init also makes the folder a Git repository.

Check it worked

Bash
uv run jupyter lab --version
uv run python -c "import pandas; print(pandas.__version__)"

The first line is 4.6.6 and the second 3.1.1, or later patch releases of each.

Step 2 · Add the data and register a kernel

Put the raw data in its own folder and make the file read-only. You will never edit it. Any cleaning happens in code, so you can always get back to the original:

Bash
mkdir -p data/raw
cat > data/raw/prices.csv <<'CSV'
market,week,crop,price_per_kg
Nairobi,2026-09-07,maize,52
Nairobi,2026-09-14,maize,54
Nairobi,2026-09-21,maize,55
Nairobi,2026-09-28,maize,58
Kisumu,2026-09-07,maize,48
Kisumu,2026-09-14,maize,47
Kisumu,2026-09-21,maize,50
Kisumu,2026-09-28,maize,53
Mombasa,2026-09-07,maize,56
Mombasa,2026-09-14,maize,56
Mombasa,2026-09-21,maize,57
Mombasa,2026-09-28,maize,57
CSV
chmod a-w data/raw/prices.csv
ls -l data/raw

Prices are in Kenyan shillings per kilogram. Now register the project's Python as a named Jupyter kernel. The kernel is the Python process that runs your code. Registering it gives it a clear name in the launcher, and lets any Jupyter install on your machine, and the headless run later, find this project's packages:

Bash
uv run python -m ipykernel install --user --name notebook-demo --display-name "Python (notebook-demo)"
uv run jupyter kernelspec list

--user writes a small folder under your home directory (~/.local/share/jupyter/kernels/notebook-demo on Linux) that points at .venv/bin/python in this project. If you move or delete the project, remove the kernel too; the last step shows how.

Check it worked

ls -l shows prices.csv with permissions -r--r--r--: nobody, including you, can write to it without changing them back. jupyter kernelspec list shows two kernels, python3 and notebook-demo, each with its folder.

Step 3 · Start JupyterLab on localhost

In your second terminal, go to the project and start the server:

Bash
cd ~/notebook-demo
uv run jupyter lab --no-browser --ip 127.0.0.1

--ip 127.0.0.1 keeps the server reachable only from your own machine. --no-browser stops it opening a tab, so you choose when to open one. The server prints a few log lines and then an address with a long random token, something like http://127.0.0.1:8888/lab?token=3f9c.... The token is the password for this session: anyone with that address can run code as you. Do not paste it into chats or screenshots, do not start the server with --ip 0.0.0.0 on a shared or café network, and never switch the token off.

Copy the full address, token included, into your browser. Leave the terminal running; closing it stops JupyterLab.

Check it worked

The browser shows JupyterLab with a file browser on the left listing data, pyproject.toml and uv.lock, and a Launcher on the right with a Python (notebook-demo) tile under Notebook. If the browser asks for a password or token instead, you copied the address without its ?token= part. Copy the whole line again from the terminal.

Step 4 · Create a notebook and learn cells and the kernel

In the Launcher, click Python (notebook-demo) under Notebook. A new Untitled.ipynb opens. Right-click it in the file browser, choose Rename, and call it scratch.ipynb.

A notebook is a list of cells. A code cell holds Python; a Markdown cell holds notes. Click into the first cell, type this, and press Shift+Enter to run it and move to the next cell:

Python
import pandas as pd

DATA = "data/raw/prices.csv"
prices = pd.read_csv(DATA)
prices.head()

The last line of a cell is shown as its output, so prices.head() draws a table of the first five rows. In the next cell, run:

Python
prices.shape

When you press Shift+Enter, JupyterLab sends the cell's code to the kernel, the separate Python process you registered. The kernel runs it and keeps every variable in memory. The .ipynb file only stores the cells and the outputs they last showed. Those are two different things, and most notebook confusion comes from forgetting it.

Diagram: on the left, the explore.ipynb file holds three numbered cells and their saved outputs; on the right, the kernel process holds the variables prices and means, plus a variable avg left over from a deleted cell. Arrows show code going to the kernel and results coming back.
The file keeps cells and outputs; the kernel keeps variables. A restart clears only the kernel.

Check it worked

The first cell shows a five-row table with the columns market, week, crop and price_per_kg. The second shows (12, 4): 12 rows and 4 columns. To the left of each cell is a number in square brackets, [1] and [2]. That is the execution count: the order in which the kernel ran the cells. The top right of the notebook shows Python (notebook-demo), the kernel it is using.

Step 5 · Catch out-of-order results with Restart and Run All

Now make the classic mistake on purpose. Add a cell that averages the price per market and run it:

Python
avg = prices.groupby("market")["price_per_kg"].mean()

Add one more cell below it and run it:

Python
avg.round(1)

It shows Kisumu 49.5, Mombasa 56.5 and Nairobi 54.8. Now go back to the avg = ... cell, rename the variable to something clearer, and run that cell again:

Python
mean_price = prices.groupby("market")["price_per_kg"].mean()

The avg.round(1) cell below still shows its numbers, and if you run it again it still works. The kernel has kept avg from the earlier run, even though no cell on the page defines it any more. Send this notebook to a colleague and it fails on their machine. Change the data and avg silently keeps the old answer.

Diagram comparing the same three cells twice. Left: after editing by hand, the execution counts read 1, 4, 3 and the avg cell works because avg survives from an earlier run. Right: after Restart and Run All, the counts read 1, 2, 3 and the avg cell fails with NameError: name 'avg' is not defined.
Counts out of page order are the warning sign. A fresh top-to-bottom run shows what the file really does.

Open the Kernel menu and choose Restart Kernel and Run All Cells…, then confirm. The kernel's memory is wiped and every cell runs once, top to bottom, the way anyone else would run your notebook.

Fix the last cell so it uses the new name, mean_price.round(1), and run Restart Kernel and Run All Cells again. Make this your habit: before you trust a number, before you share a notebook, and before you commit, restart and run all.

Check it worked

After the first restart, the avg.round(1) cell shows NameError: name 'avg' is not defined and the cells below it do not run. After the fix, every cell runs, the execution counts read [1], [2], [3] and so on from top to bottom with no gaps, and the last cell shows the three averages again.

Step 6 · Load data at the top and move reusable code into a module

A notebook that survives a restart has a simple shape: setup and data loading in the first cell, then one cell per question, each reading what earlier cells made and never changing it in place. Code you will use again, in this notebook or the next, belongs in a plain .py file. A module can be tested, imported from several notebooks and reviewed in a normal diff.

In your first terminal, in ~/notebook-demo, create prices_tools.py:

Bash
cat > prices_tools.py <<'PY'
"""Helpers for the weekly maize price data."""

import pandas as pd


def load_prices(path):
    """Read the price file with proper dates, sorted by market and week."""
    df = pd.read_csv(path, parse_dates=["week"])
    return df.sort_values(["market", "week"]).reset_index(drop=True)


def price_change(df):
    """Change in price per kg from each market's first week to its last, biggest rise first."""
    by_market = df.groupby("market")["price_per_kg"]
    change = (by_market.last() - by_market.first()).sort_values(ascending=False)
    return change.rename("change_per_kg")
PY
uv run python -c "from prices_tools import load_prices, price_change; print(price_change(load_prices('data/raw/prices.csv')))"

Back in JupyterLab, create a second notebook from the Launcher with the same Python (notebook-demo) kernel and rename it explore.ipynb. Give it these cells, in this order. Make the first one a Markdown cell (choose Markdown in the drop-down on the notebook toolbar) and the others code cells:

Markdown
# Weekly maize prices, September 2026 (practice data)

Question: which market's price per kg rose the most over the four weeks?
Python
%load_ext autoreload
%autoreload 2

from pathlib import Path

from prices_tools import load_prices, price_change

DATA = Path("data/raw/prices.csv")
prices = load_prices(DATA)
prices.head()
Python
prices.groupby("market")["price_per_kg"].mean().round(1)
Python
change = price_change(prices)
change
Python
assert len(change) == 3, "expected three markets"
print("Biggest rise:", change.index[0], change.iloc[0])

%autoreload 2 is an IPython extension that reloads prices_tools.py whenever you edit it, so you do not need to restart the kernel after every change to the module. The last cell checks an assumption with assert: if a market goes missing, the notebook stops loudly instead of printing a wrong answer. Save the notebook with Ctrl+S (Cmd+S on a Mac), then run Restart Kernel and Run All Cells. You can close scratch.ipynb; it has done its job.

Check it worked

The terminal command prints the three changes: Nairobi 6, Kisumu 5 and Mombasa 1, named change_per_kg. In the notebook, after Restart and Run All, the counts read [1] to [4] in page order and the last cell prints Biggest rise: Nairobi 6. The file browser now shows explore.ipynb, scratch.ipynb and prices_tools.py.

Step 7 · Run the notebook without a browser

nbconvert runs a notebook the way Restart and Run All does, from a terminal: fresh kernel, every cell in order, top to bottom. --inplace saves the new outputs back into the file. Run it in your first terminal:

Bash
uv run jupyter nbconvert --to notebook --execute --inplace explore.ipynb
grep "Biggest rise" explore.ipynb

nbconvert starts the kernel named in the notebook's metadata, here notebook-demo, so it uses the project's packages. If any cell raises an error, nbconvert prints the traceback and exits with a non-zero status. That makes it a cheap test: if this command passes on a clean checkout, the notebook really does run from top to bottom.

To share results with someone who does not use Jupyter, export a standalone HTML page from the outputs you just saved:

Bash
uv run jupyter nbconvert --to html explore.ipynb
ls -l explore.html

Check it worked

nbconvert logs something like [NbConvertApp] Converting notebook explore.ipynb to notebook and a Writing ... bytes line. grep prints the saved output line, "Biggest rise: Nairobi 6\n". ls shows explore.html; open it in your browser and you see the notebook's title, code, tables and output, with no server needed. If JupyterLab still has explore.ipynb open, it may say the file changed on disk; choose to revert to the version on disk.

Step 8 · Strip outputs before you commit

Outputs belong on your screen, not in version control. They make diffs unreadable, can leak data you did not mean to publish, and charts are stored as embedded images that grow a repository by megabytes per commit. That last point matters when every git push and git clone comes out of a prepaid data bundle.

nbstripout installs a Git filter that removes outputs and execution counts from notebooks as they are staged. Your working copy keeps its outputs; the commit does not. Set it up and ignore the files Git should not track:

Bash
git init
uv run nbstripout --install
git config --get filter.nbstripout.clean
cat >> .gitignore <<'EOF'
explore.html
scratch.ipynb
.ipynb_checkpoints/
EOF

git init reports that it reinitialised the repository uv init made, or makes a new one if it did not. --install writes the filter into this repository's .git/config and .git/info/attributes, so it applies here only. Now stage the project and compare what Git stored with the file on disk:

Bash
git add .gitignore .python-version pyproject.toml uv.lock prices_tools.py explore.ipynb data/raw/prices.csv
git show :explore.ipynb | grep -c '"outputs": \[\]'
grep -c '"output_type"' explore.ipynb
git commit -m "Explore weekly maize prices in a notebook"

git show :explore.ipynb prints the staged copy. Anyone who clones the repository gets the clean notebook and runs it themselves, with nbconvert or Restart and Run All, to see the outputs.

Check it worked

git config prints the filter command, something like "/home/you/notebook-demo/.venv/bin/python" -m nbstripout. The staged copy has 4 cells with "outputs": [], one for each code cell. The working copy still has 4 outputs, so JupyterLab shows your tables as before. git status after the commit lists nothing to commit except, possibly, main.py and README.md from uv init, which you can add or delete.

Step 9 · Clean up

In the second terminal, stop JupyterLab with Ctrl+C and answer y when it asks to shut down. Then remove the registered kernel before you delete the project it points at:

Bash
uv run jupyter kernelspec uninstall -y notebook-demo

The next command deletes the whole project folder, including the Git history you just made. Copy anything you want to keep first:

Bash
cd ~
rm -rf ~/notebook-demo

Check it worked

jupyter kernelspec uninstall reports that it removed the notebook-demo kernel folder, and ls ~/notebook-demo says there is no such file or directory. Python and uv stay installed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.