A project grows into several notebooks: 01_clean.ipynb, 02_features.ipynb, 03_model.ipynb. Then someone asks for the whole thing as one file, and the obvious move — open them side by side and copy cells — turns out to be the worst option. Copy-paste re-runs nothing, drops attachments, and quietly loses the outputs that made the notebook worth reading.
Merging is a data operation, not an editing one. Done properly it keeps every cell, every output and every image in the order you choose.
Why naive merging breaks
An .ipynb file is JSON with more structure than it appears to have:
- Cell IDs. nbformat 4.5 gives every cell an
id. Two notebooks can legitimately contain the same id, and a merged file with duplicates fails validation in JupyterLab. - One kernel, one metadata block. Each notebook carries its own
kernelspec. A merged file can only declare one, so the merge has to pick. - Execution counts restart.
In[17]from the second notebook next toIn[3]from the first reads like a mistake, because it is one. - Attachments are per cell. Images pasted into a markdown cell live in that cell’s
attachments. Tools that only copysourceleave a broken image reference. - Outputs are heavy. Copying cells through the clipboard often copies only the source, because that is what the editor puts on the clipboard.
Option 1: merge with nbformat (recommended for scripts)
nbformat is the library Jupyter itself uses. A merge is a dozen lines, and you can commit it next to the notebooks so the merge is reproducible.
import uuid
import nbformat
def merge_notebooks(paths, out_path):
"""Concatenate notebooks in order, keeping cells and outputs."""
merged = nbformat.v4.new_notebook()
merged.cells = []
first = None
for path in paths:
nb = nbformat.read(path, as_version=4)
if first is None:
first = nb
for cell in nb.cells:
# Fresh ids avoid validation errors from colliding cell ids.
cell["id"] = uuid.uuid4().hex[:8]
merged.cells.append(cell)
# Keep the first notebook's kernel so the file opens with the right one.
merged.metadata = first.metadata
nbformat.write(merged, out_path)
merge_notebooks(
["01_clean.ipynb", "02_features.ipynb", "03_model.ipynb"],
"report.ipynb",
)
Two details make this better than a copy-paste:
as_version=4upgrades legacy nbformat 3 files on read, so old notebooks merge cleanly.- Reassigning
cell["id"]avoids the duplicate-id validation error that appears when two notebooks were forked from the same template.
If you want section headings between the parts, insert a markdown cell before each notebook’s cells:
heading = nbformat.v4.new_markdown_cell(f"# {path.rsplit('/', 1)[-1]}")
merged.cells.append(heading)
Validate the result before sharing it:
import nbformat
nb = nbformat.read("report.ipynb", as_version=4)
nbformat.validate(nb)
print(len(nb.cells), "cells")
Option 2: the nbmerge command
nbmerge is a small CLI that does the same concatenation:
pip install nbmerge
nbmerge 01_clean.ipynb 02_features.ipynb 03_model.ipynb -o report.ipynb
It is convenient in a Makefile and has no Python boilerplate. It does not renumber execution counts or insert section headings, and it keeps the first notebook’s metadata, so the same caveats apply. If nbmerge is unavailable on your platform, the nbformat script above is the portable fallback.
Option 3: merge in the browser
For a one-off merge, the browser-based merge tool does the same job without a Python environment: choose the notebooks, set the order, and download one .ipynb with cells, outputs and attachments intact. Nothing is uploaded — the files are read and combined in the tab.
This is the route to use when you are on a locked-down machine, when the notebooks are client material, or when you need the file before you need a repeatable process.
Option 4: JupyterLab and VS Code
Both editors can combine notebooks by copying cells between tabs, and both will preserve outputs if you copy entire cells rather than the text inside them.
- JupyterLab: select cells,
Ctrl/Cmd + C, switch notebook,Ctrl/Cmd + V. Cell outputs come with them. - VS Code: drag cells between notebook editors, or use Notebook: Copy Cell and Paste.
It works for two short notebooks. It does not scale to ten, it leaves cell ids untouched, and it silently drops attachments in some versions. Treat it as a convenience, not a process.
The post-merge checklist
Run through this before you send the merged file:
- Open it in JupyterLab. Any validation error will surface immediately.
- Check the kernel. The kernel name in the status bar should match the language the cells are written in.
- Scroll for broken images. Attachments are the most common casualty of a merge.
- Look at execution counts. Either re-run the merged notebook from top to bottom, or clear outputs and accept that it is a structural document.
- Check the order. A merge is only as good as the list of files you gave it.
- Confirm the file size. Duplicated embedded images can double a notebook’s size; strip outputs if the merged file is only for reading.
If the merged notebook is going to a reviewer, the next step is usually a PDF. Convert the merged file once, rather than converting each part and stapling the results together — a single conversion gets one title block, continuous page numbers and consistent typography.
Merging is the inverse of splitting
The same structure that makes merging safe makes splitting safe. If a 60-page notebook is too much for one report, split it by heading or cell count into chapters, each with its own outputs and images, then convert the parts separately.
Either way, the rule is the same: operate on cells as data, not on text in an editor. That is what keeps the outputs, the attachments and the metadata from quietly disappearing.