Cheat Sheet Python Data Science | NumPy, Pandas, Matplotlib
1 NumPy : Tableaux & Calculs 2 Pandas : Manipulation 3 Matplotlib : Visualisation
Importation Importation Importation
import numpy as np import pandas as pd import matplotlib . pyplot as plt
Création de Tableaux (ndarrays) Structures de données 1. Méthode Fonctionnelle (plt) Simple pour les
# A partir d ’ une liste — Series : Tableau 1D avec index. graphiques rapides.
arr = np . array ([1 , 2 , 3])
mat = np . array ([[1 , 2] , [3 , 4]]) # 2 D — DataFrame : Tableau 2D (Lignes/Colonnes). x = np . linspace (1 , 2 , 20)
y = x * 2
# Initialisation specifique Chargement de données
z = np . zeros ((3 , 2) ) # Zeros plt . figure ( figsize =(10 , 6) ) # Taille
# CSV plt . plot (x , y , label = " Line 1 " , color = " r " )
o = np . ones ((3 , 2) ) # Uns df = pd . read_csv ( " data . csv " , sep = " ," , header =0)
f = np . full ((2 , 3) , 9) # Valeur 9 plt . xlabel ( " Axe X " )
e = np . eye (3) # Identite plt . ylabel ( " Axe Y " )
# Excel plt . title ( " Mon Titre " )
r = np . random . randn (3 ,3) # Aleatoire ( Normal ) df = pd . read_excel ( " data . xlsx " , sheet_name =0) plt . legend () # Affiche les labels
plt . show ()
Séquences (Très utile pour graphes) Exploration
# np . linspace ( debut , fin , nb_elements ) df . head () # 5 premieres lignes Personnalisation du plot
x = np . linspace (0 , 10 , 20) df . info () # Types et valeurs nulles
plt . plot (x , y ,
df . describe () # Stats desc ( num )
# np . arange ( debut , fin , pas ) color = " green " , # r , g , b , black ...
df . shape # ( lignes , colonnes )
y = np . arange (0 , 10 , 0.5) linestyle = " --" ,# --, -, : , -.
df . columns # Noms des colonnes
marker = " o " , # o, s, *, +
lw =2 # Largeur trait
Attributs Dimensions Sélection Filtrage )
arr . ndim # Nb dimensions # Selection Colonnes
arr . shape # Forme ( lignes , cols ) age = df [ ’ Age ’] # Serie Types de Graphiques
arr . size # Nb total elements cols = df [[ ’ Nom ’ , ’ Age ’ ]] # DataFrame
arr . dtype # Type ( int64 , float ...) plt . scatter (x , y ) # Nuage de points
# Filtres ( Masques booleens ) plt . bar (x , height ) # Barres
Remodelage (Reshape) majeurs = df [ df [ ’ Age ’] >= 18] plt . hist ( data ) # Histogramme
# Filtre conditionnel ( AND = & , OR = |)
D = np . arange (12) # 1 D (12 ,) sub = df [( df [ ’ G1 ’] < 10) & ( df [ ’ G3 ’] >= 10) ] Subplots (Grille de graphes)
R = D . reshape ((3 , 4) ) # 2 D (3 lignes , 4 cols ) # Filtre textuel
gp = df [ df [ ’ school ’] == ’ GP ’] plt . figure ()
# Aplatir (2 D -> 1 D ) # ( Lignes , Colonnes , Position )
flat = R . ravel () Manipulation plt . subplot (2 , 2 , 1)
plt . plot (x , y , c = " red " )
# Ajouter une dimension (3 ,) -> (3 ,1) # Nouvelle colonne
col = arr . reshape (( arr . shape [0] , 1) ) df [ ’ Moyenne ’] = ( df [ ’ G1 ’] + df [ ’ G2 ’ ]) / 2 plt . subplot (2 , 2 , 2)
plt . plot (x , y , c = " blue " )
Indexing & Slicing # Tri
df . sort_values ( ’ Age ’ , ascending = False ) 2. Méthode Orientée Objet (OO) Recommandée
# [ Ligne , Colonne ]
val = mat [0 , 1] # Nettoyage pour les figures complexes.
col1 = mat [: , 0] # Toute la col 0 df . d r op _ du pl i ca te s ()
lig1 = mat [0 , :] # Toute la ligne 0 # Creer Figure et Axes
fig , ax = plt . subplots (2 , 1 , figsize =(8 ,5) )
sub = mat [0:2 , 0:2] # Sous - section Agrégation (Group By)
Statistiques Maths # Moyenne par groupe # Premier graphe ( ax [0])
df . groupby ( " school " ) [ " G1 " ]. mean () ax [0]. plot (x , y )
arr . sum () # Somme totale ax [0]. set_title ( " Graphe 1 " )
arr . mean () # Moyenne # Stats multiples
arr . max () , arr . min () df . groupby ( " sex " ) [[ " G1 " , " G2 " ]]. mean () # Deuxieme graphe ( ax [1])
arr . argmax () # Index du max ax [1]. plot (x , x **2)
ax [1]. set_xlabel ( " Temps " )
Statistiques Rapides
# Calcul par axes
mat . sum ( axis =0) # Somme par colonne df [ ’ Age ’ ]. value_counts () # Comptage plt . tight_layout () # Ajuste les marges
mat . sum ( axis =1) # Somme par ligne df . corr () # Correlation plt . show ()
4 Gestion des Fichiers (I/O) — ’w’ : Écriture (Écrase le contenu). Lecture ligne par ligne (Optimisé)
— ’a’ : Ajout (Append à la fin). with open ( " data . txt " , " r " ) as f :
Ouverture (Bonne pratique) Utiliser with ferme for ligne in f :
automatiquement le fichier. — ’x’ : Création (Erreur si existe déjà). print ( ligne . strip () ) # strip enleve \ n
# Syntaxe : open ( nom , mode ) Lecture Écriture
with open ( " data . txt " , " r " ) as f :
contenu = f . read () with open ( " data . txt " , " r " ) as f : with open ( " res . txt " , " w " ) as f :
tout = f . read () # Tout le contenu f . write ( " Bonjour \ n " ) # Ecrire texte
ligne = f . readline () # Une seule ligne
Modes d’ouverture lignes = f . readlines () # Liste de lignes L = ["A\n", "B\n"]
f . writelines ( L ) # Ecrire liste
— ’r’ : Lecture seule (Erreur si absent). f . seek (0) # Revenir au debut