26/11/2025 20:40 NumPy_Etapes_FR
Parcours NumPy pas à pas (Jupyter
Notebook)
Objectif : Apprendre NumPy de manière progressive avec des exemples exécutables.
Prérequis : Python 3.x + NumPy
Astuce : exécutez les cellules du haut vers le bas.
Étape 1 : Introduction
Pourquoi NumPy ?
NumPy = Numerical Python : calcul numérique performant.
Type de base : ndarray (tableau n‑dimensions).
Très rapide par rapport aux listes Python (implémentation C).
Domaines d’usage : analyse scientifique, statistiques, traitement d’images, simulation
numérique, etc.
Installation et import
Si nécessaire :
pip install numpy
Puis dans Python :
import numpy as np
In [ ]: import numpy as np
np.__version__
Étape 2 : Créer des tableaux (Creating Arrays)
Méthodes courantes :
1. Depuis une liste Python :
[Link]([1, 2, 3])
2. Tableaux 2D / nD :
[Link]([[1, 2], [3, 4]])
3. Fonctions utilitaires :
[Link]((r, c)) — matrice de zéros
[Link]((r, c)) — matrice d’uns
[Link](n) — matrice identité
localhost:8888/lab/tree/Desktop/python avancais/numpy/NumPy_Etapes_FR.ipynb? 1/7
26/11/2025 20:40 NumPy_Etapes_FR
[Link](début, fin, pas) — suite arithmétique
[Link](début, fin, n) — n points régulièrement espacés
In [2]: import numpy as np
# Exemples
a = [Link]([1, 2, 3, 4])
b = [Link]([[1, 2], [3, 4]])
z = [Link]((2, 3))
o = [Link]((2, 3))
I = [Link](3)
ar = [Link](0, 10, 2)
ls = [Link](0, 1, 5)
print("a =", a)
print("b =\n", b)
print("zeros =\n", z)
print("ones =\n", o)
print("eye =\n", I)
print("arange =", ar)
print("linspace =", ls)
a = [1 2 3 4]
b =
[[1 2]
[3 4]]
zeros =
[[0. 0. 0.]
[0. 0. 0.]]
ones =
[[1. 1. 1.]
[1. 1. 1.]]
eye =
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
arange = [0 2 4 6 8]
linspace = [0. 0.25 0.5 0.75 1. ]
Étape 3 : Inspection des tableaux (Inspecting
Arrays)
Attributs clés :
shape : dimensions (lignes × colonnes × …)
ndim : nombre de dimensions
size : nombre total d’éléments
dtype : type des données (int, float, …)
Choisir un dtype adapté améliore la performance et la mémoire (ex.
np.float32 , np.int64 ).
In [9]: c = [Link]([[10, 20, 30], [40, 50, 60]], dtype=np.int64)
print("c =\n", c)
print("shape:", [Link])
print("ndim:", [Link])
localhost:8888/lab/tree/Desktop/python avancais/numpy/NumPy_Etapes_FR.ipynb? 2/7
26/11/2025 20:40 NumPy_Etapes_FR
print("size:", [Link])
print("dtype:", [Link])
c =
[[10 20 30]
[40 50 60]]
shape: (2, 3)
ndim: 2
size: 6
dtype: int64
Étape 4 : Opérations élément‑par‑élément (Array
Operations)
Opérations arithmétiques et fonctions mathématiques :
In [ ]: x = [Link]([1, 2, 3], dtype=np.float64)
y = [Link]([4, 5, 6], dtype=np.float64)
print("x + y =", x + y)
print("x - y =", x - y)
print("x * y =", x * y) # produit élément‑par‑élément
print("x / y =", x / y)
print("x ** 2 =", x ** 2)
print("sqrt(y) =", [Link](y))
print("exp(x) =", [Link](x))
print("log(y) =", [Link](y))
print("sin(x) =", [Link](x))
Étape 5 : Indexation et slicing (Indexing & Slicing)
1) 1D :
In [10]: v = [Link]([10, 20, 30, 40, 50])
print("v[0] =", v[0]) # premier élément
print("v[-1] =", v[-1]) # dernier élément
print("v[1:4] =", v[1:4]) # éléments 1..3
print("v[:3] =", v[:3]) # trois premiers
print("v[::2] =", v[::2]) # pas de 2
v[0] = 10
v[-1] = 50
v[1:4] = [20 30 40]
v[:3] = [10 20 30]
v[::2] = [10 30 50]
2) 2D :
In [22]: m = [Link]([[1,2,3],[4,5,6],[7,8,9]])
print("m =\n", m)
print("m[0,1] =", m[0,1]) # ligne 0, colonne 1
print("m[:,0] =", m[:,0]) # première colonne
print("m[1,:] =", m[1,:]) # deuxième ligne
print("m[1:2, 1:3] =\n", m[0:2, 1:3]) # sous‑matrice
localhost:8888/lab/tree/Desktop/python avancais/numpy/NumPy_Etapes_FR.ipynb? 3/7
26/11/2025 20:40 NumPy_Etapes_FR
m =
[[1 2 3]
[4 5 6]
[7 8 9]]
m[0,1] = 2
m[:,0] = [1 4 7]
m[1,:] = [4 5 6]
m[1:2, 1:3] =
[[2 3]
[5 6]]
Étape 6 : Statistiques de base (Statistics)
Fonctions utiles :
[Link] , [Link] , [Link] , [Link]
[Link] , [Link] , [Link]
[Link] , [Link] (indice du min/max)
Utilisables globalement ou selon un axe ( axis ).
In [1]: import numpy as np
data = [Link](4, 5) # valeurs [0,1)
print("data =\n", data)
data =
[[0.41266037 0.87844778 0.55713799 0.97806117 0.63095135]
[0.18377644 0.83207113 0.82554884 0.16060232 0.92199379]
[0.54802503 0.65110302 0.72964613 0.63642947 0.16389771]
[0.24127658 0.38598997 0.28779907 0.65780717 0.12043643]]
In [2]: print("mean =", [Link](data))
mean = 0.5401830884784784
In [3]: print("std =", [Link](data))
std = 0.2720683298976692
In [4]: print("min =", [Link](data))
min = 0.12043643015663585
In [5]: print("max =", [Link](data))
max = 0.9780611670416796
In [6]: print("sum =", [Link](data))
sum = 10.803661769569569
In [7]: print("argmin=", [Link](data), "(index dans l’array aplati)")
argmin= 19 (index dans l’array aplati)
In [8]: print("argmax=", [Link](data), "(index dans l’array aplati)")
argmax= 3 (index dans l’array aplati)
localhost:8888/lab/tree/Desktop/python avancais/numpy/NumPy_Etapes_FR.ipynb? 4/7
26/11/2025 20:40 NumPy_Etapes_FR
In [10]: print("mean(axis=0) =", [Link](data, axis=0))
print("mean(axis=1) =", [Link](data, axis=1))
mean(axis=0) = [0.14364926 0.19338658 0.20432019 0.2917185 0.33378165]
mean(axis=1) = [0.20810458 0.33869344 0.19947738 0.18099002]
In [ ]: data = [Link](4, 5) # valeurs [0,1)
print("data =\n", data)
print("\nStats globales :")
print("mean =", [Link](data))
print("std =", [Link](data))
print("min =", [Link](data))
print("max =", [Link](data))
print("sum =", [Link](data))
print("argmin=", [Link](data), "(index dans l’array aplati)")
print("argmax=", [Link](data), "(index dans l’array aplati)")
print("\nPar axe (axis=0 : colonnes, axis=1 : lignes) :")
print("mean(axis=0) =", [Link](data, axis=0))
print("mean(axis=1) =", [Link](data, axis=1))
Étape 7 : Reshape & Assemblage (Reshaping &
Combining)
reshape(r, c, …) : reconfigurer les dimensions (sans changer les données).
Assembler des tableaux :
[Link]((A, B), axis=…)
[Link]((A, B)) (empiler verticalement)
[Link]((A, B)) (empiler horizontalement)
In [ ]: arr = [Link](12)
print("arr =", arr)
reshaped = [Link](3, 4)
print("\nreshaped (3x4) =\n", reshaped)
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print("\nA =\n", A)
print("B =\n", B)
print("\nconcatenate axis=0 =\n", [Link]((A,B), axis=0))
print("concatenate axis=1 =\n", [Link]((A,B), axis=1))
print("\nvstack =\n", [Link]((A,B)))
print("hstack =\n", [Link]((A,B)))
Étape 8 : Masques booléens (Boolean Masking)
Filtrer/sélectionner/modifier des éléments via des conditions logiques, sans boucles
for .
localhost:8888/lab/tree/Desktop/python avancais/numpy/NumPy_Etapes_FR.ipynb? 5/7
26/11/2025 20:40 NumPy_Etapes_FR
In [ ]: w = [Link]([10, 15, 22, 5, 30, 7])
mask = w > 10
print("w =", w)
print("mask =", mask)
print("w[mask] =", w[mask]) # éléments > 10
w2 = [Link]()
w2[w2 < 10] = 0
print("\nw2 modifié =", w2)
Étape 9 : Broadcasting & Vectorization
Broadcasting
Permet d’opérer entre tableaux de tailles différentes si les dimensions sont compatibles.
Vectorization
Remplacer des boucles explicites par des opérations vectorisées rapides.
In [ ]: # Broadcasting
u = [Link]([1, 2, 3])
scalar = 2
print("u * scalar =", u * scalar)
M = [Link]([[1,2,3],[4,5,6]])
v = [Link]([10, 20, 30])
print("\nM + v =\n", M + v)
# Vectorization vs boucle (démo simple)
big = [Link](100_000, dtype=np.float64)
vec_res = big * 1.5 + 2.0
vec_res[:5]
Étape 10 : Exercices pratiques
Ajoutez des cellules pour vos solutions sous chaque consigne :
1. Créez une matrice aléatoire 10×10 (valeurs dans [0,1)), puis :
calculez moyenne, écart‑type, min, max ;
sélectionnez toutes les valeurs > 0.7 via un masque booléen.
2. Créez une matrice 5×5 d’entiers aléatoires entre 1 et 100, puis :
remplacez toutes les valeurs paires par 0 ;
calculez la somme par colonne ( axis=0 ) et la moyenne par ligne ( axis=1 ).
3. Créez un vecteur 1×1 000 000 de valeurs aléatoires et comparez le temps de deux
approches :
boucle for appliquant x = x*1.1 + 3 ;
opération vectorisée équivalente.
localhost:8888/lab/tree/Desktop/python avancais/numpy/NumPy_Etapes_FR.ipynb? 6/7
26/11/2025 20:40 NumPy_Etapes_FR
Utilisez %%time dans une cellule Jupyter pour chronométrer.
Conseils
Choisissez des dtype appropriés pour la performance/mémoire.
Préférez les opérations vectorisées aux boucles.
Comprenez bien shape et axis — fondamental pour déboguer les erreurs de
dimensions.
Affichez les shape des tableaux concernés quand une opération échoue.
NumPy + Pandas + Matplotlib = trio puissant pour l’analyse.
Généré le : 2025-10-23 05:30
localhost:8888/lab/tree/Desktop/python avancais/numpy/NumPy_Etapes_FR.ipynb? 7/7