Skip to content

commandData and AIpython

Clean Notebook

Cleans a Jupyter notebook: removes dead cells, fixes run order, moves reusable code into modules and checks it runs top to bottom.

npx workspacetemplates add clean-notebook --tool claude-code

Writes 1 file to .claude/commands/

.claude/commands/clean-notebook.md16 lines · 1.2 KBFile
---
description: "Cleans a Jupyter notebook: removes dead cells, fixes run order, moves reusable code into modules and checks it runs top to bottom."
argument-hint: "[path to the .ipynb file]"
---

Clean up the notebook: $ARGUMENTS

1. Copy it to `<name>.backup.ipynb` before touching anything.
2. Read all cells with `jupyter nbconvert --to script` or by parsing the JSON. List cells that are empty, commented-out experiments, duplicated, or never referenced by later cells.
3. Find hidden state: variables used before they are defined in file order, cells that depend on a manual run order, and hard-coded absolute paths or credentials. Move paths to variables at the top.
4. Propose the cleanup list and ask for approval before deleting any cell.
5. Move functions used by more than one cell into `<name>_lib.py` beside the notebook with docstrings, and import them. Keep exploratory plotting in the notebook.
6. Order cells: imports, config, load, transform, analyze, plot. Add a short markdown heading before each section.
7. Clear outputs, then verify with `jupyter nbconvert --to notebook --execute --inplace` on a copy.

Report cells removed, code moved, and whether the notebook runs top to bottom.

What it does

Notebooks grow messy: cells run out of order, abandoned experiments, hidden state that only works on your machine. This command proves what the notebook really depends on and tidies it into something others can rerun.

Reusable functions move into a Python module with imports in the notebook, and outputs are cleared. The original is backed up first, so you can always return to it.

Example

you › /clean-notebook analysis/churn.ipynb

agent › Backup saved. 112 cells: 19 empty or dead, 7 duplicates, 3 cells rely on state from a later cell.
Moved 6 functions to churn_lib.py, replaced /Users/me/data with DATA_DIR.
Fresh top-to-bottom run passes in 41s. Apply the deletions?

Questions

Is my original notebook kept?
Yes. A backup copy is made before any edit and the run check uses a copy.
Does it delete cells without asking?
No. It lists them and waits for your approval first.
  • Analyze CSV

    Commandpython

    Free
  • Eval Prompt

    CommandData and AI

    Free
  • Profile DataFrame

    Commandpython

    Free
  • SQL From Question

    CommandData and AI

    Free