Zum Inhalt

_

_ _ _

_

Jupyter Notebook Cheatsheet

• Installation

Platform Command
Ubuntu/Debian INLINE_CODE_26____HTML_TAG_226____INLINE_CODE_27
RHEL/CentOS/Fedora INLINE_CODE_28____HTML_TAG_227____INLINE_CODE_29
macOS (pip) INLINE_CODE_30
macOS (Homebrew) INLINE_CODE_31____HTML_TAG_228____INLINE_CODE_32
Windows INLINE_CODE_33
Anaconda (all platforms) INLINE_CODE_34
JupyterLab INLINE_CODE_35
Docker INLINE_CODE_36____HTML_TAG_229____INLINE_CODE_37
Virtual Environment INLINE_CODE_38____HTML_TAG_230____INLINE_CODE_39____HTML_TAG_231____INLINE_CODE_40
_
oder Grundlegende Befehle
Command Description
INLINE_CODE_41 Start Jupyter Notebook server (opens browser automatically)
INLINE_CODE_42 Start server on specific port
INLINE_CODE_43 Start server without opening browser
INLINE_CODE_44 Start server with specific working directory
INLINE_CODE_45 Start server accessible on all network interfaces
INLINE_CODE_46 List all running notebook servers
INLINE_CODE_47 Stop server running on port 8888
INLINE_CODE_48 Start JupyterLab (next-generation interface)
INLINE_CODE_49 Show all Jupyter configuration paths
INLINE_CODE_50 Show Jupyter configuration directory
INLINE_CODE_51 Show Jupyter data directory
INLINE_CODE_52 List all available kernels
INLINE_CODE_53 Show Jupyter version information
_
Tastenkombinationen - Befehlsmodus

Drücken Esc, um Befehlsmodus einzutragen (Zellgrenze ist blau)

Shortcut Action
INLINE_CODE_55 Enter Edit Mode
INLINE_CODE_56 or INLINE_CODE_57 Move to cell above
INLINE_CODE_58 or INLINE_CODE_59 Move to cell below
INLINE_CODE_60 Insert cell above current cell
INLINE_CODE_61 Insert cell below current cell
INLINE_CODE_62 Delete selected cell(s)
INLINE_CODE_63 Cut selected cell(s)
INLINE_CODE_64 Copy selected cell(s)
INLINE_CODE_65 Paste cell(s) below
INLINE_CODE_66 Paste cell(s) above
INLINE_CODE_67 Undo cell deletion
INLINE_CODE_68 Change cell to Code type
INLINE_CODE_69 Change cell to Markdown type
INLINE_CODE_70 Change cell to Raw type
INLINE_CODE_71 Run cell and select cell below
INLINE_CODE_72 Run cell in place
INLINE_CODE_73 Run cell and insert new cell below
INLINE_CODE_74 Select multiple cells
INLINE_CODE_75 Merge selected cells
INLINE_CODE_76 Save notebook
INLINE_CODE_77 Toggle line numbers
INLINE_CODE_78 Toggle cell output
INLINE_CODE_79 Toggle output scrolling
INLINE_CODE_80 Show keyboard shortcuts help
INLINE_CODE_81 Interrupt kernel
INLINE_CODE_82 Restart kernel
_
Tastenkombinationen - Bearbeitungsmodus

Drücken Sie Enter auf einer Zelle, um Edit Mode einzutragen (Zellgrenze ist grün)

Shortcut Action
INLINE_CODE_84 Enter Command Mode
INLINE_CODE_85 Run cell and select cell below
INLINE_CODE_86 Run cell in place
INLINE_CODE_87 Run cell and insert new cell below
INLINE_CODE_88 Undo
INLINE_CODE_89 Redo
INLINE_CODE_90 Select all text in cell
INLINE_CODE_91 Toggle comment on selected lines
INLINE_CODE_92 Code completion or indent
INLINE_CODE_93 Show function tooltip/documentation
INLINE_CODE_94 (×2) Expand tooltip
INLINE_CODE_95 (×4) Show full documentation in pager
INLINE_CODE_96 Indent
INLINE_CODE_97 Dedent
INLINE_CODE_98 Go to cell start
INLINE_CODE_99 Go to cell end
_
oder Line Magic Commands

Line Magics starten mit __INLINE_CODE_100_ und arbeiten auf einer einzigen Linie

Command Description
INLINE_CODE_101 List all available magic commands
INLINE_CODE_102 Show quick reference for IPython
INLINE_CODE_103 Show detailed documentation for magic commands
INLINE_CODE_104 Execute external Python script
INLINE_CODE_105 Execute script with command-line arguments
INLINE_CODE_106 Load external file into current cell
INLINE_CODE_107 Load file from URL into current cell
INLINE_CODE_108 Time execution of single statement
INLINE_CODE_109 Time execution with multiple runs for accuracy
INLINE_CODE_110 Print current working directory
INLINE_CODE_111 Change working directory
INLINE_CODE_112 List files in current directory
INLINE_CODE_113 Show all environment variables
INLINE_CODE_114 Set environment variable
INLINE_CODE_115 List all variables in namespace
INLINE_CODE_116 List all variables with detailed information
INLINE_CODE_117 List variables of specific type
INLINE_CODE_118 Delete all variables from namespace
INLINE_CODE_119 Force reset without confirmation
INLINE_CODE_120 Display matplotlib plots inline
INLINE_CODE_121 Enable interactive matplotlib plots
INLINE_CODE_122 High-resolution plots for retina displays
INLINE_CODE_123 Enable automatic debugger on exception
INLINE_CODE_124 Disable automatic debugger
INLINE_CODE_125 Profile function execution
INLINE_CODE_126 Show command history
INLINE_CODE_127 Show specific range of history
INLINE_CODE_128 Recall and execute command from history
INLINE_CODE_129 Re-execute previous command
INLINE_CODE_130 Bookmark directory with name
INLINE_CODE_131 Change to bookmarked directory
_
In den Warenkorb

Zellzauber starten mit __INLINE_CODE_132_ und arbeiten auf der gesamten Zelle

Command Description
INLINE_CODE_133 Time execution of entire cell
INLINE_CODE_134 Time cell execution with multiple runs
INLINE_CODE_135 Capture cell output to variable
INLINE_CODE_136 Write cell contents to file
INLINE_CODE_137 Append cell contents to file
INLINE_CODE_138 Execute cell as bash script
INLINE_CODE_139 Execute cell as shell script
INLINE_CODE_140 Execute cell with specific interpreter
INLINE_CODE_141 Render cell as HTML
INLINE_CODE_142 Execute cell as JavaScript
INLINE_CODE_143 Render cell as LaTeX
INLINE_CODE_144 Render cell as Markdown
INLINE_CODE_145 Render cell as SVG
INLINE_CODE_146 Execute cell as Perl script
INLINE_CODE_147 Execute cell as Ruby script
_
oder Shell Commands
Command Description
INLINE_CODE_148 Execute shell command
INLINE_CODE_149 Install Python package
INLINE_CODE_150 List installed packages
INLINE_CODE_151 Check Python version
INLINE_CODE_152 Capture shell output to variable
INLINE_CODE_153 Use Python variable in shell command
INLINE_CODE_154 Repeat last shell command

Fortgeschrittene magische Befehle

Command Description
INLINE_CODE_155 Load autoreload extension
INLINE_CODE_156 Automatically reload changed modules
INLINE_CODE_157 Load line profiler extension
INLINE_CODE_158 Profile function line-by-line
INLINE_CODE_159 Load memory profiler extension
INLINE_CODE_160 Measure memory usage of code
INLINE_CODE_161 Load SQL magic extension
INLINE_CODE_162 Execute SQL query (requires connection)
INLINE_CODE_163 Load Cython extension
INLINE_CODE_164 Compile cell with Cython
INLINE_CODE_165 Set exception mode (Plain/Context/Verbose)
INLINE_CODE_166 Enter debugger after exception
INLINE_CODE_167 Print last exception traceback
INLINE_CODE_168 Create macro from cells 1-5
INLINE_CODE_169 Store variable for use in other notebooks
INLINE_CODE_170 Restore stored variable
_
Kernel Management
Command Description
INLINE_CODE_171 List all installed kernels
INLINE_CODE_172 List kernels in JSON format
INLINE_CODE_173 Install Python kernel from environment
INLINE_CODE_174 Install kernel with custom display name
INLINE_CODE_175 Remove installed kernel
INLINE_CODE_176 Install kernel from directory

Zusätzliche Sprachkerne installieren

# 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

Erweiterungen und Anpassung

Command Description
INLINE_CODE_177 Install community extensions
INLINE_CODE_178 Enable extensions configurator
INLINE_CODE_179 List all installed extensions
INLINE_CODE_180 Enable specific extension
INLINE_CODE_181 Disable specific extension
INLINE_CODE_182 Install interactive widgets
INLINE_CODE_183 Enable widgets extension
INLINE_CODE_184 Install theme customization tool
INLINE_CODE_185 List available themes
INLINE_CODE_186 Apply theme
INLINE_CODE_187 Reset to default theme
INLINE_CODE_188 Install extension configurator UI

Beliebte Erweiterungen

# 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

Konfiguration

Konfigurationsdatei generieren

jupyter notebook --generate-config

Konfigurationsdatei-Standorte: Linux/macOS: ~/.jupyter/jupyter_notebook_config.py_ - Windows: C:\Users\USERNAME\.jupyter\jupyter_notebook_config.py

Gemeinsame Konfigurationsoptionen

# 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

Passwort festlegen

# 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

Erstellen ~/.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;
}

Individuelles JavaScript

Erstellen ~/.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;
};

Häufige Anwendungsfälle

Use Case 1: Datenanalyse 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: Automatisiertes Reporting mit 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 Formatierung in Zellen

Headers

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

Textformatierung

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

Listen

# 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)

Tabellen

| 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

`markdownpython def hello(): Print("Hello World") _`

Blockquotes

CODE_BLOCK_20

Horizontal Rule

CODE_BLOCK_21

Best Practices

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

  • 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 CODE_BLOCK_23

  • Use Cell Output Wisely: Clear unnecessary output before saving (Cell → Alle Ausgabe → 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__INLINE_CODE_198_%time_, %timeit__, and _%prun________________________%_____%_______%____________________________________________________________________________________________________________________________________________________ autoreload__INLINE_CODE_202_%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 CODE_BLOCK_24

  • Use Requirements Files: Document dependencies in requires.txt___INLINE_CODE_204_%memit_. Reduce data size, use chunking for large files, or increase available RAM. Check logs with jupyter Notebook --debug_LINE_IN_CODE_206__jupyter Kernelspec Liste. 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___INLINE_CODE_209_jupyter notebook list__INLINE_CODE_210_jupyter notebook /full/path/to/notebook.ipynb | | Can't access notebook from remote machine | Ensure Jupyter is bound to 0.0_: jupyter Notizbuch --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 → Alle Ausgabe → Clear. Check for infinite loops or memory leaks in code | | "JavaScript output is disabled in JupyterLab" | Enable JavaScript: Einstellungen → Erweiterte Einstellungen Editor → Notebook → "sanitizer": {"allowNamedProperties": true}__INLINE_CODE_217_jupyter Notebook passwort_. Delete token file: `rm ~/.jupyter/jupyter_notebook_config.json__INLINE_CODE_219_jupyter Notizbuch --NotebookApp