Saltar a contenido

Jupyter Notebook Cheatsheet

Instalación

__TABLE_233_

Comandos básicos

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

Keyboard Shortcuts - Command Mode

Pulse Esc_ para entrar en el Modo de Mando (la frontera celular es azul)

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

Atajos de teclado - Modo de edición

Pulse Enter_ en una celda para entrar en el modo Editar (la frontera celular es verde)

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

Comandos Mágicos de Línea

Las magias de línea comienzan con __INLINE_CODE_100_ y operan en una sola línea

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

Cell Magic Commands

Las magias de las células comienzan con __INLINE_CODE_132_ y operan en toda la célula

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

Comandos Shell

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

Advanced Magic Commands

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

Instalación de núcleos de lenguaje adicional

# 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

Extensiones y personalización

__TABLE_242_

Extensiones populares

# 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

Configuración

Generar archivo de configuración

jupyter notebook --generate-config

Localizaciones de archivos de configuración: Linux/macOS: ~/.jupyter/jupyter_notebook_config.py - ¿Qué?

Opciones de configuración común

# 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

Establecer contraseña

# 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;
}

JavaScript personalizado

Crear ~/.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

`markdownpython def hola(): print("Hola Mundo") _`

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 → 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____CODE_199___%timeit______CODE_200__%prun______CODE_201__%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 CODE_BLOCK_24

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

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 portátil --ip=0.0.0.0. Check firewall allows port 8888. Create SSH tunnel: _ssh -L 8888:localhost:88 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__INLINE_CODE_219_jupyter portátil --NotebookApp