Skip to content

Jupyter Notebook Cheatsheet

Installation

Platform Command
Ubuntu/Debian sudo apt update && sudo apt install python3-pip
pip3 install jupyter
RHEL/CentOS/Fedora sudo dnf install python3-pip python3-devel
pip3 install jupyter
macOS (pip) pip3 install jupyter
macOS (Homebrew) brew install python
pip3 install jupyter
Windows pip install jupyter
Anaconda (all platforms) conda install jupyter
JupyterLab pip install jupyterlab
Docker docker pull jupyter/datascience-notebook
docker run -p 8888:8888 jupyter/datascience-notebook
Virtual Environment python3 -m venv jupyter-env
source jupyter-env/bin/activate
pip install jupyter

Basic Commands

Command Description
jupyter notebook Start Jupyter Notebook server (opens browser automatically)
jupyter notebook --port=8889 Start server on specific port
jupyter notebook --no-browser Start server without opening browser
jupyter notebook /path/to/dir Start server with specific working directory
jupyter notebook --ip=0.0.0.0 Start server accessible on all network interfaces
jupyter notebook list List all running notebook servers
jupyter notebook stop 8888 Stop server running on port 8888
jupyter lab Start JupyterLab (next-generation interface)
jupyter --paths Show all Jupyter configuration paths
jupyter --config-dir Show Jupyter configuration directory
jupyter --data-dir Show Jupyter data directory
jupyter kernelspec list List all available kernels
jupyter --version Show Jupyter version information

Keyboard Shortcuts - Command Mode

Press Esc to enter Command Mode (cell border is blue)

Shortcut Action
Enter Enter Edit Mode
or k Move to cell above
or j Move to cell below
a Insert cell above current cell
b Insert cell below current cell
dd Delete selected cell(s)
x Cut selected cell(s)
c Copy selected cell(s)
v Paste cell(s) below
Shift+v Paste cell(s) above
z Undo cell deletion
y Change cell to Code type
m Change cell to Markdown type
r Change cell to Raw type
Shift+Enter Run cell and select cell below
Ctrl+Enter Run cell in place
Alt+Enter Run cell and insert new cell below
Shift+↑/↓ Select multiple cells
Shift+m Merge selected cells
Ctrl+s Save notebook
l Toggle line numbers
o Toggle cell output
Shift+o Toggle output scrolling
h Show keyboard shortcuts help
ii Interrupt kernel
00 Restart kernel

Keyboard Shortcuts - Edit Mode

Press Enter on a cell to enter Edit Mode (cell border is green)

Shortcut Action
Esc Enter Command Mode
Shift+Enter Run cell and select cell below
Ctrl+Enter Run cell in place
Alt+Enter Run cell and insert new cell below
Ctrl+z Undo
Ctrl+Shift+z Redo
Ctrl+a Select all text in cell
Ctrl+/ Toggle comment on selected lines
Tab Code completion or indent
Shift+Tab Show function tooltip/documentation
Shift+Tab (×2) Expand tooltip
Shift+Tab (×4) Show full documentation in pager
Ctrl+] Indent
Ctrl+[ Dedent
Ctrl+Home Go to cell start
Ctrl+End Go to cell end

Line Magic Commands

Line magics start with % and operate on a single line

Command Description
%lsmagic List all available magic commands
%quickref Show quick reference for IPython
%magic Show detailed documentation for magic commands
%run script.py Execute external Python script
%run script.py arg1 arg2 Execute script with command-line arguments
%load script.py Load external file into current cell
%load https://url.com/file.py Load file from URL into current cell
%time statement Time execution of single statement
%timeit statement Time execution with multiple runs for accuracy
%pwd Print current working directory
%cd /path/to/dir Change working directory
%ls List files in current directory
%env Show all environment variables
%env VAR=value Set environment variable
%who List all variables in namespace
%whos List all variables with detailed information
%who_ls str List variables of specific type
%reset Delete all variables from namespace
%reset -f Force reset without confirmation
%matplotlib inline Display matplotlib plots inline
%matplotlib notebook Enable interactive matplotlib plots
%config InlineBackend.figure_format='retina' High-resolution plots for retina displays
%pdb on Enable automatic debugger on exception
%pdb off Disable automatic debugger
%prun function() Profile function execution
%history Show command history
%history -n 1-10 Show specific range of history
%recall 5 Recall and execute command from history
%rerun Re-execute previous command
%bookmark name /path Bookmark directory with name
%cd -b name Change to bookmarked directory

Cell Magic Commands

Cell magics start with %% and operate on entire cell

Command Description
%%time Time execution of entire cell
%%timeit Time cell execution with multiple runs
%%capture output Capture cell output to variable
%%writefile file.py Write cell contents to file
%%writefile -a file.py Append cell contents to file
%%bash Execute cell as bash script
%%sh Execute cell as shell script
%%script python3 Execute cell with specific interpreter
%%html Render cell as HTML
%%javascript Execute cell as JavaScript
%%latex Render cell as LaTeX
%%markdown Render cell as Markdown
%%svg Render cell as SVG
%%perl Execute cell as Perl script
%%ruby Execute cell as Ruby script

Shell Commands

Command Description
!ls -la Execute shell command
!pip install pandas Install Python package
!pip list List installed packages
!python --version Check Python version
files = !ls Capture shell output to variable
!echo {variable} Use Python variable in shell command
!! Repeat last shell command

Advanced Magic Commands

Command Description
%load_ext autoreload Load autoreload extension
%autoreload 2 Automatically reload changed modules
%load_ext line_profiler Load line profiler extension
%lprun -f func func() Profile function line-by-line
%load_ext memory_profiler Load memory profiler extension
%memit code Measure memory usage of code
%load_ext sql Load SQL magic extension
%%sql SELECT * FROM table Execute SQL query (requires connection)
%load_ext cython Load Cython extension
%%cython Compile cell with Cython
%xmode Plain Set exception mode (Plain/Context/Verbose)
%debug Enter debugger after exception
%tb Print last exception traceback
%macro name 1-5 Create macro from cells 1-5
%store variable Store variable for use in other notebooks
%store -r variable Restore stored variable

Kernel Management

Command Description
jupyter kernelspec list List all installed kernels
jupyter kernelspec list --json List kernels in JSON format
python -m ipykernel install --user --name=env Install Python kernel from environment
python -m ipykernel install --user --name=env --display-name="My Env" Install kernel with custom display name
jupyter kernelspec remove kernel_name Remove installed kernel
jupyter kernelspec install /path/to/kernel Install kernel from directory

Installing Additional Language Kernels

# R Kernel
# In R console:
install.packages('IRkernel')
IRkernel::installspec()

# Julia Kernel
# In Julia REPL:
using Pkg
Pkg.add("IJulia")

# JavaScript (Node.js) Kernel
npm install -g ijavascript
ijsinstall

# Bash Kernel
pip install bash_kernel
python -m bash_kernel.install

Extensions and Customization

Command Description
pip install jupyter_contrib_nbextensions Install community extensions
jupyter contrib nbextension install --user Enable extensions configurator
jupyter nbextension list List all installed extensions
jupyter nbextension enable extension/main Enable specific extension
jupyter nbextension disable extension/main Disable specific extension
pip install ipywidgets Install interactive widgets
jupyter nbextension enable --py widgetsnbextension Enable widgets extension
pip install jupyterthemes Install theme customization tool
jt -l List available themes
jt -t theme_name Apply theme
jt -r Reset to default theme
pip install jupyter_nbextensions_configurator Install extension configurator UI
# Table of Contents
jupyter nbextension enable toc2/main

# Code Folding
jupyter nbextension enable codefolding/main

# Execute Time
jupyter nbextension enable execute_time/ExecuteTime

# Variable Inspector
jupyter nbextension enable varInspector/main

# Collapsible Headings
jupyter nbextension enable collapsible_headings/main

# Autopep8 (code formatter)
jupyter nbextension enable code_prettify/autopep8

Configuration

Generate Configuration File

jupyter notebook --generate-config

Configuration file locations: - Linux/macOS: ~/.jupyter/jupyter_notebook_config.py - Windows: C:\Users\USERNAME\.jupyter\jupyter_notebook_config.py

Common Configuration Options

# jupyter_notebook_config.py

# Network settings
c.NotebookApp.ip = '0.0.0.0'  # Listen on all interfaces
c.NotebookApp.port = 8888  # Default port
c.NotebookApp.open_browser = False  # Don't open browser automatically

# Security settings
c.NotebookApp.password = 'sha1:...'  # Hashed password (use jupyter notebook password)
c.NotebookApp.token = ''  # Disable token authentication (not recommended)
c.NotebookApp.allow_root = False  # Prevent running as root

# Directory settings
c.NotebookApp.notebook_dir = '/path/to/notebooks'  # Default notebook directory

# HTTPS settings
c.NotebookApp.certfile = '/path/to/cert.pem'
c.NotebookApp.keyfile = '/path/to/key.key'

# Kernel settings
c.NotebookApp.kernel_spec_manager_class = 'jupyter_client.kernelspec.KernelSpecManager'

# Logging
c.NotebookApp.log_level = 'INFO'  # DEBUG, INFO, WARN, ERROR, CRITICAL

# Shutdown behavior
c.NotebookApp.shutdown_no_activity_timeout = 3600  # Seconds of inactivity before shutdown

Set Password

# Set notebook password
jupyter notebook password

# Or programmatically in Python:
from notebook.auth import passwd
passwd()  # Enter password, copy the hash to config file

Custom CSS

Create ~/.jupyter/custom/custom.css:

/* Increase cell width */
.container {
    width: 95% !important;
}

/* Change code font */
.CodeMirror {
    font-family: 'Monaco', monospace;
    font-size: 12pt;
}

/* Customize cell output */
div.output_area {
    background-color: #f5f5f5;
    padding: 10px;
}

Custom JavaScript

Create ~/.jupyter/custom/custom.js:

// Auto-save every 2 minutes
setInterval(function() {
    Jupyter.notebook.save_checkpoint();
}, 120000);

// Disable autoscroll
IPython.OutputArea.prototype._should_scroll = function() {
    return false;
};

Common Use Cases

Use Case 1: Data Analysis Workflow

# Import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

# Load data
df = pd.read_csv('data.csv')

# Quick exploration
df.head()
df.info()
df.describe()

# Visualization
df.plot(kind='scatter', x='column1', y='column2', figsize=(10, 6))
plt.title('My Analysis')
plt.show()

# Export results
df.to_csv('results.csv', index=False)

Use Case 2: Machine Learning Model Development

# Import libraries
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

# Load and prepare data
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
%time model.fit(X_train, y_train)

# Evaluate
predictions = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, predictions):.4f}")
print(classification_report(y_test, predictions))

# Feature importance visualization
feature_importance = pd.DataFrame({
    'feature': X.columns,
    'importance': model.feature_importances_
}).sort_values('importance', ascending=False)

feature_importance.plot(x='feature', y='importance', kind='barh', figsize=(10, 8))

Use Case 3: Interactive Report Generation

# Create interactive widgets
import ipywidgets as widgets
from IPython.display import display

# Dropdown for data filtering
column_selector = widgets.Dropdown(
    options=df.columns.tolist(),
    description='Column:',
    disabled=False,
)

# Slider for threshold
threshold = widgets.FloatSlider(
    value=50,
    min=0,
    max=100,
    step=1,
    description='Threshold:',
)

def update_plot(column, threshold_value):
    filtered_df = df[df[column] > threshold_value]
    filtered_df[column].hist(bins=30, figsize=(10, 6))
    plt.title(f'{column} > {threshold_value}')
    plt.show()

# Interactive output
widgets.interactive(update_plot, column=column_selector, threshold_value=threshold)

Use Case 4: Remote Server Setup

# On remote server
jupyter notebook --generate-config

# Set password
jupyter notebook password

# Edit config file
nano ~/.jupyter/jupyter_notebook_config.py

# Add these lines:
# c.NotebookApp.ip = '0.0.0.0'
# c.NotebookApp.port = 8888
# c.NotebookApp.open_browser = False

# Start server
jupyter notebook

# On local machine, create SSH tunnel
ssh -N -f -L localhost:8888:localhost:8888 user@remote-server

# Access in browser: http://localhost:8888

Use Case 5: Automated Reporting with Papermill

# Install papermill
pip install papermill

# Execute notebook with parameters
papermill input_notebook.ipynb output_notebook.ipynb \
    -p start_date '2024-01-01' \
    -p end_date '2024-12-31' \
    -p region 'US'

# Convert to HTML report
jupyter nbconvert --to html output_notebook.ipynb

# Batch processing multiple notebooks
for region in US EU ASIA; do
    papermill template.ipynb report_${region}.ipynb -p region $region
    jupyter nbconvert --to pdf report_${region}.ipynb
done

Markdown Formatting in Cells

Headers

# Heading 1
## Heading 2
### Heading 3
#### Heading 4

Text Formatting

**bold text**
*italic text*
***bold and italic***
~~strikethrough~~
`inline code`

Lists

# Unordered list
- Item 1
- Item 2
  - Sub-item 2.1
  - Sub-item 2.2

# Ordered list
1. First item
2. Second item
3. Third item
[Link text](https://example.com)
![Alt text](image.png)
![Remote image](https://example.com/image.jpg)

Tables

| Column 1 | Column 2 | Column 3 |
|----------|----------|----------|
| Value 1  | Value 2  | Value 3  |
| Value 4  | Value 5  | Value 6  |

LaTeX Math

Inline math: $E = mc^2$

Display math:
$$
\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
$$

Code Blocks

```python
def hello():
    print("Hello World")
```

Blockquotes

> This is a blockquote
> It can span multiple lines

Horizontal Rule

---

Best Practices

  • Use Virtual Environments: Always work within virtual environments to isolate project dependencies and avoid conflicts

    python -m venv project_env
    source project_env/bin/activate  # Linux/macOS
    project_env\Scripts\activate  # Windows
    pip install jupyter
    

  • Organize Notebooks Logically: Use clear naming conventions (e.g., 01_data_loading.ipynb, 02_preprocessing.ipynb) and keep notebooks focused on single tasks or analyses

  • Document Your Code: Use Markdown cells liberally to explain your thought process, methodology, and findings. Include section headers, explanations, and conclusions

  • Restart and Run All Regularly: Before sharing or deploying, use "Kernel → Restart & Run All" to ensure your notebook executes cleanly from top to bottom without hidden state dependencies

  • Keep Cells Small and Focused: Break complex operations into multiple cells for easier debugging and testing. Each cell should perform one logical operation

  • Version Control with Git: Add notebooks to Git repositories, but consider using nbstripout to remove output before committing

    pip install nbstripout
    nbstripout --install  # Set up Git filter
    

  • Use Cell Output Wisely: Clear unnecessary output before saving (Cell → All Output → Clear) to reduce file size and improve readability

  • Enable Autosave and Create Checkpoints: Jupyter autosaves every 2 minutes by default. Manually save frequently with Ctrl+S and create checkpoints before major changes

  • Leverage Magic Commands: Use %time, %timeit, and %prun to profile code performance. Use %load_ext autoreload and %autoreload 2 during development

  • Secure Remote Notebooks: Always use passwords and HTTPS when exposing Jupyter to networks. Consider using JupyterHub for multi-user environments

  • Export and Share Appropriately: Convert notebooks to appropriate formats for sharing

    jupyter nbconvert --to html notebook.ipynb  # For viewing
    jupyter nbconvert --to pdf notebook.ipynb   # For reports
    jupyter nbconvert --to script notebook.ipynb  # For Python scripts
    

  • Use Requirements Files: Document dependencies in requirements.txt for reproducibility

    pip freeze > requirements.txt
    pip install -r requirements.txt
    

Troubleshooting

Issue Solution
Kernel keeps dying or restarting Check for memory issues with %memit. Reduce data size, use chunking for large files, or increase available RAM. Check logs with jupyter notebook --debug
"Connection failed" or "Kernel not found" Ensure kernel is properly installed: jupyter kernelspec list. Reinstall kernel: python -m ipykernel install --user. Check firewall settings if accessing remotely
ModuleNotFoundError even after pip install Kernel may be using different Python environment. Install package in correct environment: !pip install package_name from notebook, or activate correct environment before starting Jupyter
Notebook won't open or shows 404 error Check if server is running: jupyter notebook list. Verify notebook path is correct. Try starting with full path: jupyter notebook /full/path/to/notebook.ipynb
Can't access notebook from remote machine Ensure Jupyter is bound to 0.0.0.0: jupyter notebook --ip=0.0.0.0. Check firewall allows port 8888. Create SSH tunnel: ssh -L 8888:localhost:8888 user@remote
Slow performance or high CPU usage Disable extensions: jupyter nbextension disable extension_name. Clear output: Cell → All Output → Clear. Check for infinite loops or memory leaks in code
"JavaScript output is disabled in JupyterLab" Enable JavaScript: Settings → Advanced Settings Editor → Notebook → "sanitizer": {"allowNamedProperties": true} or use Jupyter Notebook instead of Lab
Token/password not working Reset token: jupyter notebook password. Delete token file: rm ~/.jupyter/jupyter_notebook_config.json. Start with no token (insecure): `jupyter notebook --NotebookApp