1. Introduction à NumPy et aux ndarray
1.1 Qu'est-ce que NumPy ?
NumPy est la bibliothèque fondamentale pour le calcul scientifique en Python. Elle fournit l'objet ndarray (N-dimensional array) qui permet des opérations numériques efficaces grâce à la vectorisation.
1.2 Installation et importation
|
1 2 3 4 5 6 7 8 |
# Installation (via terminal) # pip install numpy # Importation standard import numpy as np # Vérification de la version print(f"NumPy version: {np.__version__}") |
2. Création et Initialisation de Tableaux
2.1 Création de tableaux de base
|
1 2 3 4 5 6 7 8 9 10 11 |
# À partir d'une liste Python arr1 = np.array([1, 2, 3, 4, 5]) print("Tableau 1D:", arr1) # Tableau 2D arr2 = np.array([[1, 2, 3], [4, 5, 6]]) print("Tableau 2D:\n", arr2) # Tableau 3D arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) print("Dimensions arr3:", arr3.shape) |
2.2 Fonctions de création spécialisées
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Zéros zeros_arr = np.zeros((3, 4)) print("Zéros 3x4:\n", zeros_arr) # Uns ones_arr = np.ones((2, 3, 2)) print("Uns 2x3x2:\n", ones_arr) # Matrice identité identity = np.eye(4) print("Matrice identité 4x4:\n", identity) # Tableau vide (non initialisé) empty_arr = np.empty((2, 2)) print("Tableau vide:\n", empty_arr) # Plage de valeurs range_arr = np.arange(0, 10, 2) # 0 à 10 exclus, pas de 2 print("Arange:", range_arr) # Linspace (nombre d'éléments fixe) lin_arr = np.linspace(0, 1, 5) # 5 valeurs entre 0 et 1 print("Linspace:", lin_arr) |
3. Propriétés et Manipulation des Tableaux
3.1 Attributs fondamentaux
|
1 2 3 4 5 6 7 8 9 |
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("Tableau:\n", arr) print("Dimensions (shape):", arr.shape) print("Nombre de dimensions (ndim):", arr.ndim) print("Nombre total d'éléments (size):", arr.size) print("Type des données (dtype):", arr.dtype) print("Taille en octets d'un élément (itemsize):", arr.itemsize) print("Taille totale en octets (nbytes):", arr.nbytes) |
3.2 Types de données (dtype)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Spécification du type de données arr_int = np.array([1, 2, 3], dtype=np.int32) arr_float = np.array([1.1, 2.2, 3.3], dtype=np.float64) arr_complex = np.array([1+2j, 3+4j], dtype=np.complex128) arr_bool = np.array([True, False, True], dtype=np.bool_) print("int32:", arr_int.dtype) print("float64:", arr_float.dtype) print("complex128:", arr_complex.dtype) print("bool:", arr_bool.dtype) # Conversion de type arr_float_converted = arr_int.astype(np.float64) print("Conversion int32 vers float64:", arr_float_converted.dtype) |
4. Indexing, Slicing et Indexation Avancée
4.1 Indexing et slicing basique
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Indexing print("Élément (0,0):", arr[0, 0]) print("Élément (2,3):", arr[2, 3]) # Slicing print("Première ligne:", arr[0, :]) print("Deuxième colonne:", arr[:, 1]) print("Sous-matrice 2x2:", arr[0:2, 1:3]) print("Toutes les lignes, colonnes paires:", arr[:, ::2]) # Modification via slicing arr_slice = arr[:2, :2] arr_slice[:, :] = 0 print("Tableau modifié:\n", arr) |
4.2 Indexation booléenne et par tableau
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Indexation booléenne mask = arr > 5 print("Masque (arr > 5):", mask) print("Éléments > 5:", arr[mask]) # Indexation avec liste d'indices indices = [0, 2, 4, 6] print("Éléments aux indices [0,2,4,6]:", arr[indices]) # Indexation avancée 2D arr_2d = np.array([[1, 2], [3, 4], [5, 6]]) rows = [0, 1, 2] cols = [1, 0, 1] print("Éléments (0,1), (1,0), (2,1):", arr_2d[rows, cols]) |
5. Opérations Mathématiques et Vectorisation
5.1 Opérations arithmétiques de base
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
a = np.array([1, 2, 3, 4]) b = np.array([5, 6, 7, 8]) print("Addition:", a + b) print("Soustraction:", a - b) print("Multiplication:", a * b) print("Division:", b / a) print("Exponentiation:", a ** 2) print("Racine carrée:", np.sqrt(a)) # Opérations avec scalaires print("Addition scalaire:", a + 10) print("Multiplication scalaire:", a * 3) |
5.2 Fonctions universelles (ufuncs)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
arr = np.array([-2, -1, 0, 1, 2]) # Fonctions mathématiques print("Valeur absolue:", np.abs(arr)) print("Exponentielle:", np.exp(arr)) print("Logarithme népérien:", np.log(np.abs(arr) + 1)) print("Sinus:", np.sin(arr)) print("Cosinus:", np.cos(arr)) # Fonctions statistiques print("Somme:", np.sum(arr)) print("Moyenne:", np.mean(arr)) print("Écart-type:", np.std(arr)) print("Minimum:", np.min(arr)) print("Maximum:", np.max(arr)) print("Indice du minimum:", np.argmin(arr)) print("Indice du maximum:", np.argmax(arr)) |
5.3 Broadcasting
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Broadcasting: étendre les dimensions automatiquement matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) vector = np.array([10, 20, 30]) # Le vecteur est broadcasté sur chaque ligne result = matrix + vector print("Matrix + Vector (broadcasting):\n", result) # Broadcasting avec reshape explicite vector_col = vector.reshape(3, 1) result2 = matrix + vector_col print("Matrix + Vector colonne:\n", result2) |
6. Manipulation de la Forme et Combinaison
6.1 Reshape, resize et flatten
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
arr = np.arange(12) print("Tableau original (1D):", arr) # Reshape (créé une nouvelle vue si possible) arr_2d = arr.reshape(3, 4) print("Reshape 3x4:\n", arr_2d) arr_3d = arr.reshape(2, 3, 2) print("Reshape 2x3x2:\n", arr_3d) # Resize (modifie le tableau original) arr_copy = arr.copy() arr_copy.resize(2, 6) print("Resize 2x6:\n", arr_copy) # Flatten et ravel flattened = arr_2d.flatten() # Copie raveled = arr_2d.ravel() # Vue si possible print("Flatten:", flattened) print("Ravel:", raveled) |
6.2 Concatenation et séparation
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 6], [7, 8]]) # Concatenation print("Concatenation axe 0 (lignes):\n", np.concatenate([a, b], axis=0)) print("Concatenation axe 1 (colonnes):\n", np.concatenate([a, b], axis=1)) print("vstack (vertical):\n", np.vstack([a, b])) print("hstack (horizontal):\n", np.hstack([a, b])) # Séparation arr = np.arange(12).reshape(3, 4) print("Tableau à séparer:\n", arr) print("Split en 2 tableaux:\n", np.split(arr, 2, axis=1)) print("vsplit:\n", np.vsplit(arr, 3)) print("hsplit:\n", np.hsplit(arr, 2)) |
6.3 Opérations d'algèbre linéaire
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Produit matriciel print("Produit matriciel A.B:\n", np.dot(A, B)) print("Produit matriciel (opérateur @):\n", A @ B) # Transposition print("Transposée de A:\n", A.T) # Déterminant et inverse from numpy.linalg import det, inv print("Déterminant de A:", det(A)) print("Inverse de A:\n", inv(A)) # Valeurs et vecteurs propres from numpy.linalg import eig eigenvalues, eigenvectors = eig(A) print("Valeurs propres:", eigenvalues) print("Vecteurs propres:\n", eigenvectors) |
Younes Derfoufi
CRMEF OUJDA



