Vai al contenuto
__HTML_TAG_221_📋 Copia tutti i comandi della cartella di note di Jupyter_HTML_TAG_222__ __HTML_TAG_223_📄 Generare Jupyter Notebook PDF Guida_HTML_TAG_224__

Jupyter Notebook Cheatsheet

Installazione

Tabella_233_

Comandi di base

Tabella_234_

Tastiera Scorciatoie - Modalità di comando

Premere Esc per entrare in Modalità Comando (il bordo cellulare è blu) Tabella_235

Tastiera Scorciatoie - Modifica Modalità

Premere Enter su una cella per inserire Modifica Modalità (il bordo cellulare è verde) Tabella_236_

Linea Comandi Magici

Le magie di linea iniziano con % e operano su una singola linea Tabella_237_

Comandi magici delle celle

Le magie cellulari iniziano con %% e funzionano su tutta la cella Tabella_238_

Comandi di Shell

Tabella_239_

Comandi magici avanzati

Tabella_240_

Kernel Management

Tabella_241_

Installazione di Kernel linguistici aggiuntivi

# 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

Estensioni e personalizzazione

Tabella_242_

Estensioni popolari

# 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

Configurazione

Generate Configuration File

jupyter notebook --generate-config

Posizione dei file di configurazione: - Linux/macOS ~/.jupyter/jupyter_notebook_config.py - **Windows **

Opzioni di configurazione comuni

# 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

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

Crea ~/.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 personalizzato

Crea ~/.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: Impostazione server remoto

# 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: Reporting automatizzato con 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 Formattazione nelle celle

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

Formattazione del testo

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

Liste

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

Tavoli

| 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

Traduzione: (in inglese) stampa("Hello World") __________________________________________________ → Tutte le uscite → Clear___INLINE_CODE_197_Ctrl+S_INLINE_CODE_198__%time,%timeit_, and%prun_to profile code performance. Use%load_ext autoreloadand% autoreload 2_INLINE_CODE_203__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__INLINE_CODE_206_jupyter kernelspec Traduzione: -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___INLINE_CODE_210_jupyter notebook /full/path/to/to/notebook.ipynb___INLINE_CODE_211_0.0_INLINE_CODE_212_jupyter notebook --ip=0.0.0.0_INLINE_CODE_213_ssh -L 8888:localhost:8888 user@remote__INLINE_CODE_214_jupyter nbextension disable extension_name__INLINE_CODE_215_Cell → Tutte le uscite → Clear. Check for infinite loops or memory leaks in code
"JavaScript output is disabled in JupyterLab" Enable JavaScript: `Settings → Editor di impostazioni avanzate → Notebook → "sanitizer": {"allowNamedProperties": true}_INLINE_CODE_217_jupyter notebook password__INLINE_CODE_218_rm ~/.jupyter/jupyter_notebook_config.json_INLINE_CODE_219_jupyter notebook - NotebookApp