0%
Jupyter: Notebooks and JupyterLab for Data Science

Jupyter: Notebooks and JupyterLab for Data Science

A complete guide to Jupyter Notebook and JupyterLab: installation, kernel configuration, magic commands, extensions, and best practices for data science in Python.

I

InSkillCoach

· min

Jupyter: Notebooks and JupyterLab for Data Science

Jupyter Notebook is the tool of choice for data scientists and researchers working in Python. It combines executable code, Markdown documentation, visualizations, and text output in a single interactive document. JupyterLab, the modern Jupyter interface, extends this experience with a file browser, an integrated terminal, and full extensibility. This guide shows you how to install, configure, and master Jupyter to develop and document your data analyses.

1. Installation and Configuration

Installing with pip

# Installation de base
# pip install jupyter

# Installation avec support complet
# pip install jupyterlab

# Vérifier l'installation
# jupyter --version
# jupyter kernelspec list

Installing via pip is recommended in a dedicated virtual environment to avoid dependency conflicts.

# Créer un environnement virtuel
# python -m venv env_jupyter
# source env_jupyter/bin/activate  # Sur Linux/macOS
# env_jupyter\Scripts\activate      # Sur Windows

# Installer Jupyter dans cet environnement
# pip install jupyterlab numpy pandas matplotlib

Virtual Environments and Kernels

Each Python environment should have its own Jupyter kernel. A kernel is the process that runs the code in your notebook.

# Créer un environnement pour data science
# python -m venv ds_env
# source ds_env/bin/activate
# pip install ipykernel

# Enregistrer ce kernel auprès de Jupyter
# python -m ipykernel install --user --name ds_env --display-name "Python (DS)"

# Créer un autre environnement pour du développement web
# python -m venv web_env
# source web_env/bin/activate
# pip install ipykernel flask django

# Enregistrer ce kernel
# python -m ipykernel install --user --name web_env --display-name "Python (Web)"

# Lister tous les kernels disponibles
# jupyter kernelspec list

Once your kernels are registered, you can switch between them in Jupyter using the “Kernel” menu or from the bottom right of the notebook.

2. Notebook vs. JupyterLab

Classic Notebook

Jupyter Notebook is a minimalist, lightweight interface. You launch it with:

# jupyter notebook
# Cette commande ouvre une interface web à http://localhost:8888

Advantages of the classic Notebook:

  • Lightweight, with low resource usage
  • Simple, with few distractions
  • Fast startup

JupyterLab

JupyterLab is the next generation of Jupyter, with a modular and extensible interface.

# jupyter lab
# Cette commande ouvre JupyterLab à http://localhost:8888

Advantages of JupyterLab:

  • Multiple files open in tabs
  • Built-in file browser on the left
  • Integrated terminal and console
  • Native image viewer
  • Extensibility through TypeScript/JavaScript plugins
  • Collapsible sidebar

3. Cell Structure

Code Cell

A code cell contains executable Python. You run it by pressing Ctrl+Enter (or Cmd+Enter on Mac).

# Cellule de code

import numpy as np

data = np.array([1, 2, 3, 4, 5])
moyenne = data.mean()

print(f"Moyenne : {moyenne}")
# Affichage : Moyenne : 3.0

The execution order is determined by the number in square brackets: [1], [2], and so on. You can re-run a cell as many times as you like, and the execution order changes.

Markdown Cell

Markdown cells let you document your analyses with formatted text, headings, lists, and mathematical formulas.

# Titre principal

## Sous-titre

Ceci est un paragraphe contenant du texte en **gras** et en *italique*.

- Élément 1
- Élément 2
- Élément 3

### Formules LaTeX

Voici une formule inline : $y = mx + b$

Et une formule centrée :

$$\sum_{i=1}^{n} x_i = \frac{n(n+1)}{2}$$

Tip: press Ctrl+Enter to run (render) a Markdown cell, or press Esc then M to convert a code cell to Markdown.

4. Essential Keyboard Shortcuts

ShortcutModeAction
Ctrl+EnterEdit/CmdRun the cell
Shift+EnterEditRun and move to the next cell
Alt+EnterEditRun and insert a new cell
EscEditSwitch to command mode
EnterCommandSwitch to edit mode
ACommandInsert a cell above
BCommandInsert a cell below
D DCommandDelete the cell (press D twice)
MCommandConvert to Markdown
YCommandConvert to Code
Ctrl+Shift+PCommandCommand palette
HCommandShow the shortcuts help

5. Magic Commands

Magic commands are special shortcuts prefixed with % (line) or %% (cell). They make debugging and optimization easier.

%timeit: Measuring execution time

# Mesurer le temps d'une ligne

%timeit sum(range(100))
# Résultat : 1.25 µs ± 41.2 ns per loop (mean ± std. dev. of 7 runs)

%%time: Timing an entire cell

%%time

# Calcul complet de la cellule
resultat = sum(range(1_000_000))
print(resultat)
# CPU times: user 23.4 ms, sys: 1.23 ms, total: 24.6 ms
# Wall time: 25.1 ms

%matplotlib inline

Displays Matplotlib charts directly in the notebook (required before using Matplotlib).

%matplotlib inline

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Courbe simple")
plt.show()
# Le graphique s'affiche directement sous la cellule

%run: Running an external Python file

# Supposons que vous ayez un fichier helper.py
# contenant des fonctions réutilisables

%run helper.py

# Les fonctions et variables du fichier sont maintenant disponibles
print(ma_fonction(5))

%pip: Installing packages directly in the notebook

# Installer une bibliothèque sans quitter le notebook
%pip install requests

import requests
# Utiliser la bibliothèque immédiatement

%pwd and %cd: Navigating the file system

%pwd
# Affiche le répertoire courant
# /Users/utilisateur/projects/analysis

%cd ../data
# Change le répertoire courant

%ls
# Liste les fichiers du répertoire courant

6. Rich Display and Output

Jupyter can display much more than text: images, formatted DataFrames, HTML, LaTeX, and more.

from IPython.display import display, HTML, Image, DataFrame
import pandas as pd

# Afficher du HTML
display(HTML("<h3 style='color:red;'>Attention!</h3>"))
# Résultat : Attention! (en rouge et gros)

# Afficher une image depuis une URL
display(Image(url="https://example.com/image.png"))

# DataFrame Pandas avec formatage automatique
df = pd.DataFrame({
    'Nom': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Ville': ['Paris', 'Lyon', 'Marseille']
})

display(df)
# Affiche un tableau formaté et interactif

7. Useful Extensions and Plugins

JupyterLab has a rich ecosystem of extensions to enhance the experience.

Managing extensions

# Lister les extensions installées
# jupyter labextension list

# Installer une extension
# jupyter labextension install @jupyter-widgets/jupyterlab-manager

# Vérifier les extensions depuis la ligne de commande
# pip install jupyterlab_execute_time
# pip install jupyterlab-code-formatter
# pip install jupyterlab-lsp
ExtensionPurpose
jupyterlab-execute-timeDisplays the execution time of each cell
jupyterlab-code-formatterFormats Python code (Black, Autopep8, etc.)
jupyterlab-lspSupport for Language Server Protocol servers (advanced autocompletion)
ipywidgetsInteractive widgets (sliders, buttons, etc.)
jupyterlab-gitGit integration directly in JupyterLab

8. Exporting and Converting with nbconvert

An .ipynb notebook is just a JSON file. You can export your work to other formats.

# Exporter en PDF (nécessite pandoc et LaTeX)
# jupyter nbconvert --to pdf notebook.ipynb

# Exporter en HTML statique
# jupyter nbconvert --to html notebook.ipynb
# Résultat : notebook.html

# Exporter en Python pur (cellules code uniquement)
# jupyter nbconvert --to python notebook.ipynb
# Résultat : notebook.py

# Exporter en Markdown
# jupyter nbconvert --to markdown notebook.ipynb

# Exporter en slides (révélation.js)
# jupyter nbconvert --to slides notebook.ipynb --post serve

9. Versioning Notebooks with Git

.ipynb files are difficult to version with Git. Several strategies exist:

The native problem

// notebook.ipynb est un JSON avec des sorties, métadonnées, etc.
{
  "cells": [...],
  "metadata": {...},
  "nbformat": 4,
  "nbformat_minor": 5
}
// Les diffs sont illisibles, les fusions sont impossibles

Solution 1: Strip outputs before committing

# nbstripout : enlève les sorties et métadonnées superflues
# pip install nbstripout

# git config filter.strip-notebook.clean "nbstripout"
# Ajouter à .gitattributes :
# *.ipynb filter=strip-notebook

Solution 2: Keep the Python code alongside

# Exporter régulièrement en Python
# jupyter nbconvert --to python notebook.ipynb

# Versionner notebook.py au lieu de notebook.ipynb
# Les diffs sont clairs et les fusions faciles

Solution 3: Use Jupyter Book or Quarto

For a serious project, migrate to Jupyter Book (.md + code) or Quarto (a universal format), which are better suited to version control.

10. Best Practices

  • One section = one notebook: keep one notebook per analysis topic. Very long notebooks become hard to navigate.
  • Short, focused cells: each cell should do one thing. This makes debugging and reuse easier.
  • Document with Markdown: don’t hesitate to write Markdown cells explaining your steps. Notebooks are also a way to tell a story.
  • Clean up before sharing: remove test cells, temporary variables, and stale outputs. Export or re-run everything from scratch before delivering.
  • Use explicitly named variables: df_sales_2024 rather than df1.
  • Save regularly: Jupyter autosaves, but a manual save (Ctrl+S) never hurts.
  • Restart the kernel before sharing: use the “Kernel” menu → “Restart & Run All” to verify that everything runs in order.

11. Alternatives and Complements

ToolUse case
VS Code + JupyterIf you prefer VS Code to a web interface
Google ColabFree notebooks in the cloud, with free GPUs/TPUs
Kaggle NotebooksData science competitions and collaborative notebooks
Pluto.jlReactive notebooks for Julia (similar concept)
ObservableJavaScript notebooks for web visualization

Conclusion

Jupyter Notebook and JupyterLab have become essential in the Python ecosystem for data science, machine learning, and research. Their combination of executable code, documentation, and interactive visualization makes them the ideal environment for exploring data, prototyping models, and communicating your results. By mastering magic commands, keyboard shortcuts, and extensions, you will significantly boost your productivity. Keep in mind that Jupyter is not a production tool: for robust analysis pipelines, prefer well-organized Python scripts that are properly tested and versioned.

InSkillCoach

About InSkillCoach

Training and technology expert

Coach specializing in advanced technologies and AI, backed by GNeurone Inc.

Certifications:

  • AWS Certified Solutions Architect – Professional
  • Google Cloud certifications
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
1.2k
264

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!