Numpy¶

In [1]:
import numpy as np
In [2]:
ma_liste = [1,20,13,40,25]
In [3]:
# Afficher la liste
ma_liste
# ou print(ma_liste)
Out[3]:
[1, 20, 13, 40, 25]
In [4]:
# creer un vecteur numpy a partir d'une liste
mon_vecteur = np.array(ma_liste)
In [5]:
mon_vecteur
Out[5]:
array([ 1, 20, 13, 40, 25])
In [6]:
# Acceder au deuxieme element
mon_vecteur[1]
Out[6]:
20
In [8]:
mon_vecteur[-4]
Out[8]:
20
In [9]:
# accerder au dernier element
mon_vecteur[4]
Out[9]:
25
In [10]:
mon_vecteur[-1]
Out[10]:
25
In [11]:
# accerder au 2eme 3eme et 4eme element
# mon_vecteur[1:4]
# ou 
mon_vecteur[-4:-1]
Out[11]:
array([20, 13, 40])
In [12]:
mon_vecteur[1:4]
Out[12]:
array([20, 13, 40])
In [13]:
# Les matrice
ma_liste2 = [1,-20,3,4,50]
ma_liste2
Out[13]:
[1, -20, 3, 4, 50]
In [14]:
ma_matrice = [ma_liste,ma_liste2]
ma_matrice
Out[14]:
[[1, 20, 13, 40, 25], [1, -20, 3, 4, 50]]
In [15]:
ma_matrice_np = np.array(ma_matrice)
ma_matrice_np
Out[15]:
array([[  1,  20,  13,  40,  25],
       [  1, -20,   3,   4,  50]])
In [16]:
# premiere ligne
ma_matrice_np[0]
Out[16]:
array([ 1, 20, 13, 40, 25])
In [17]:
# 3eme element de la premiere ligne
ma_matrice_np[0][2]
Out[17]:
13
In [18]:
ma_matrice_np[-1][-2]
Out[18]:
4
In [20]:
ma_matrice_np[-1][3]
Out[20]:
4

Pandas¶

In [21]:
# premiere etape: il faut importer la librairie pandas
import pandas as pd
In [24]:
# charger la base de données
df =pd.read_csv("DBM1.csv",sep=';')
df.head() # affiche les 05 premières lignes
Out[24]:
T P S F C
0 180 70 h 2 brun
1 177 57 h 3 brun
2 180 60 h 1 bleu
3 180 66 h 0 brun
4 183 62 h 6 vert
In [25]:
# afficher les 05 dernières lignes
df.tail()
Out[25]:
T P S F C
40 158 62 f 0 brun
41 161 65 f 1 brun
42 160 61 f 1 bleu
43 162 58 f 2 brun
44 165 58 f 5 brun
In [26]:
# Afficher la dimmension
#df.shape
df.shape
Out[26]:
(45, 5)
In [27]:
# afficher les colonnes
df.columns
Out[27]:
Index(['T', 'P', 'S', 'F', 'C'], dtype='object')
In [28]:
# Afficher les types des colonnes
df.dtypes
Out[28]:
T     int64
P     int64
S    object
F     int64
C    object
dtype: object
In [29]:
# infos sur les donnees
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 45 entries, 0 to 44
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   T       45 non-null     int64 
 1   P       45 non-null     int64 
 2   S       45 non-null     object
 3   F       45 non-null     int64 
 4   C       45 non-null     object
dtypes: int64(3), object(2)
memory usage: 1.9+ KB
In [30]:
# Description des données
df.describe()
Out[30]:
T P F
count 45.000000 45.000000 45.000000
mean 174.311111 65.088889 1.933333
std 8.836449 8.953979 1.601136
min 157.000000 47.000000 0.000000
25% 167.000000 59.000000 1.000000
50% 177.000000 65.000000 2.000000
75% 181.000000 71.000000 3.000000
max 190.000000 98.000000 7.000000
In [31]:
df.describe(include ='all')
Out[31]:
T P S F C
count 45.000000 45.000000 45 45.000000 45
unique NaN NaN 2 NaN 5
top NaN NaN h NaN brun
freq NaN NaN 30 NaN 23
mean 174.311111 65.088889 NaN 1.933333 NaN
std 8.836449 8.953979 NaN 1.601136 NaN
min 157.000000 47.000000 NaN 0.000000 NaN
25% 167.000000 59.000000 NaN 1.000000 NaN
50% 177.000000 65.000000 NaN 2.000000 NaN
75% 181.000000 71.000000 NaN 3.000000 NaN
max 190.000000 98.000000 NaN 7.000000 NaN
In [32]:
df.describe(include ='object')
Out[32]:
S C
count 45 45
unique 2 5
top h brun
freq 30 23
In [33]:
# afficher la colonne T
df['T'].head()
Out[33]:
0    180
1    177
2    180
3    180
4    183
Name: T, dtype: int64
In [34]:
# afficher la colonne C
df['C'].head()
Out[34]:
0    brun
1    brun
2    bleu
3    brun
4    vert
Name: C, dtype: object
In [35]:
# afficher les colonnes P et S
df[['P','S']].head()
Out[35]:
P S
0 70 h
1 57 h
2 60 h
3 66 h
4 62 h
In [36]:
# decrire la variable T
df['T'].describe()
Out[36]:
count     45.000000
mean     174.311111
std        8.836449
min      157.000000
25%      167.000000
50%      177.000000
75%      181.000000
max      190.000000
Name: T, dtype: float64
In [37]:
# calculer explicitement des parametres statistique
# df['T'].mean()
# df['T'].std()
#df['T'].min()
#df['T'].max()
df['T'].median()
Out[37]:
177.0
In [38]:
df['T'].mean()
Out[38]:
174.3111111111111
In [39]:
df['T'].std()
Out[39]:
8.836448850235499
In [40]:
df['T'].min()
Out[40]:
157
In [41]:
df['T'].max()
Out[41]:
190
In [42]:
# afficher la 1ere taille
df['T'][0]
Out[42]:
180
In [43]:
# afficher la 10ieme taille
df['T'][9]
Out[43]:
180
In [44]:
# afficher la 6ieme taille
df['T'][5]
Out[44]:
184
In [46]:
# trier les valeurs
df['T'].sort_values().head()
Out[46]:
31    157
40    158
42    160
41    161
43    162
Name: T, dtype: int64
In [47]:
## tri généralisé d'un data frame
# trier le data set par ordre croissant de T
df.sort_values(by ='T')
Out[47]:
T P S F C
31 157 47 f 1 vert
40 158 62 f 0 brun
42 160 61 f 1 bleu
41 161 65 f 1 brun
43 162 58 f 2 brun
34 163 65 f 1 brun
37 164 49 f 7 vert
44 165 58 f 5 brun
39 165 59 f 2 bleu
36 166 68 f 2 bleu
32 167 53 f 2 vert
35 167 60 f 2 brun
17 167 60 h 4 bleu
33 168 57 f 4 bleu
10 168 52 h 3 brun
30 168 52 f 0 brun
21 170 68 h 1 gris
22 170 59 h 3 brun
38 172 57 f 3 brun
20 173 75 h 1 vert
8 174 65 h 3 noir
27 176 65 h 1 vert
1 177 57 h 3 brun
28 178 72 h 1 brun
19 179 98 h 2 brun
24 179 73 h 3 vert
0 180 70 h 2 brun
14 180 65 h 4 brun
2 180 60 h 1 bleu
25 180 72 h 3 bleu
3 180 66 h 0 brun
9 180 72 h 2 brun
11 180 75 h 0 bleu
18 181 67 h 0 brun
13 181 68 h 0 bleu
4 183 62 h 6 vert
23 183 72 h 2 bleu
16 183 78 h 0 bleu
12 183 75 h 2 brun
7 184 72 h 2 brun
5 184 68 h 0 brun
6 185 65 h 1 noir
29 185 71 h 1 bleu
26 188 70 h 2 brun
15 190 66 h 1 brun
In [48]:
# trier le data set par ordre croissant de T puis de P
df.sort_values(by =['T','P'])
Out[48]:
T P S F C
31 157 47 f 1 vert
40 158 62 f 0 brun
42 160 61 f 1 bleu
41 161 65 f 1 brun
43 162 58 f 2 brun
34 163 65 f 1 brun
37 164 49 f 7 vert
44 165 58 f 5 brun
39 165 59 f 2 bleu
36 166 68 f 2 bleu
32 167 53 f 2 vert
17 167 60 h 4 bleu
35 167 60 f 2 brun
10 168 52 h 3 brun
30 168 52 f 0 brun
33 168 57 f 4 bleu
22 170 59 h 3 brun
21 170 68 h 1 gris
38 172 57 f 3 brun
20 173 75 h 1 vert
8 174 65 h 3 noir
27 176 65 h 1 vert
1 177 57 h 3 brun
28 178 72 h 1 brun
24 179 73 h 3 vert
19 179 98 h 2 brun
2 180 60 h 1 bleu
14 180 65 h 4 brun
3 180 66 h 0 brun
0 180 70 h 2 brun
9 180 72 h 2 brun
25 180 72 h 3 bleu
11 180 75 h 0 bleu
18 181 67 h 0 brun
13 181 68 h 0 bleu
4 183 62 h 6 vert
23 183 72 h 2 bleu
12 183 75 h 2 brun
16 183 78 h 0 bleu
5 184 68 h 0 brun
7 184 72 h 2 brun
6 185 65 h 1 noir
29 185 71 h 1 bleu
26 188 70 h 2 brun
15 190 66 h 1 brun
In [49]:
##  Acces indicé au données d'un dataFrame avec loc et iloc

# acces a la cellule d'indice (0,0)
df.iloc[0,0]
Out[49]:
180
In [50]:
# acces a la cellule d'indice (42,2)
df.iloc[42,2]
Out[50]:
'f'
In [51]:
# cinq premieres lignes
df.iloc[0:5,:]
Out[51]:
T P S F C
0 180 70 h 2 brun
1 177 57 h 3 brun
2 180 60 h 1 bleu
3 180 66 h 0 brun
4 183 62 h 6 vert
In [52]:
# deux premieres colonnes
df.iloc[:,0:2]
Out[52]:
T P
0 180 70
1 177 57
2 180 60
3 180 66
4 183 62
5 184 68
6 185 65
7 184 72
8 174 65
9 180 72
10 168 52
11 180 75
12 183 75
13 181 68
14 180 65
15 190 66
16 183 78
17 167 60
18 181 67
19 179 98
20 173 75
21 170 68
22 170 59
23 183 72
24 179 73
25 180 72
26 188 70
27 176 65
28 178 72
29 185 71
30 168 52
31 157 47
32 167 53
33 168 57
34 163 65
35 167 60
36 166 68
37 164 49
38 172 57
39 165 59
40 158 62
41 161 65
42 160 61
43 162 58
44 165 58
In [53]:
### les requetes
# Lister les hommes
df.loc[df['S']=="h",:]
Out[53]:
T P S F C
0 180 70 h 2 brun
1 177 57 h 3 brun
2 180 60 h 1 bleu
3 180 66 h 0 brun
4 183 62 h 6 vert
5 184 68 h 0 brun
6 185 65 h 1 noir
7 184 72 h 2 brun
8 174 65 h 3 noir
9 180 72 h 2 brun
10 168 52 h 3 brun
11 180 75 h 0 bleu
12 183 75 h 2 brun
13 181 68 h 0 bleu
14 180 65 h 4 brun
15 190 66 h 1 brun
16 183 78 h 0 bleu
17 167 60 h 4 bleu
18 181 67 h 0 brun
19 179 98 h 2 brun
20 173 75 h 1 vert
21 170 68 h 1 gris
22 170 59 h 3 brun
23 183 72 h 2 bleu
24 179 73 h 3 vert
25 180 72 h 3 bleu
26 188 70 h 2 brun
27 176 65 h 1 vert
28 178 72 h 1 brun
29 185 71 h 1 bleu
In [54]:
# Lister les femmes
df.loc[df['S']=="f",:]
Out[54]:
T P S F C
30 168 52 f 0 brun
31 157 47 f 1 vert
32 167 53 f 2 vert
33 168 57 f 4 bleu
34 163 65 f 1 brun
35 167 60 f 2 brun
36 166 68 f 2 bleu
37 164 49 f 7 vert
38 172 57 f 3 brun
39 165 59 f 2 bleu
40 158 62 f 0 brun
41 161 65 f 1 brun
42 160 61 f 1 bleu
43 162 58 f 2 brun
44 165 58 f 5 brun
In [55]:
# les hommes ayant des yeux bleu ou noir
df2= df.loc[df['S']=="h",:]
df2.loc[df2['C'].isin(['bleu']),:]
Out[55]:
T P S F C
2 180 60 h 1 bleu
11 180 75 h 0 bleu
13 181 68 h 0 bleu
16 183 78 h 0 bleu
17 167 60 h 4 bleu
23 183 72 h 2 bleu
25 180 72 h 3 bleu
29 185 71 h 1 bleu
In [56]:
# les hommes ayant des yeux bleu ou noir
df2= df.loc[df['S']=="h",:]
df2.loc[df2['C'].isin(['bleu','noir']),:]
Out[56]:
T P S F C
2 180 60 h 1 bleu
6 185 65 h 1 noir
8 174 65 h 3 noir
11 180 75 h 0 bleu
13 181 68 h 0 bleu
16 183 78 h 0 bleu
17 167 60 h 4 bleu
23 183 72 h 2 bleu
25 180 72 h 3 bleu
29 185 71 h 1 bleu
In [57]:
# utilisation des operateurs logiques
# ET = &
# OU = |
# Negation - tilde

# les hommes ayant des yeux bleu
df.loc[(df['S']=="h") & (df['C']=="bleu"),:]
Out[57]:
T P S F C
2 180 60 h 1 bleu
11 180 75 h 0 bleu
13 181 68 h 0 bleu
16 183 78 h 0 bleu
17 167 60 h 4 bleu
23 183 72 h 2 bleu
25 180 72 h 3 bleu
29 185 71 h 1 bleu
In [58]:
# les femmes ayant des yeux bleu ou noir
df.loc[((df['S']=="f") & (df['C']=="bleu"))| ((df['S']=="f") & (df['C']=="noir")),:]
Out[58]:
T P S F C
33 168 57 f 4 bleu
36 166 68 f 2 bleu
39 165 59 f 2 bleu
42 160 61 f 1 bleu
In [61]:
# #liste des personnes de moins de 75 kilos, de sexe masculin, présentant ayant des yeux noir
df.loc[(df['P'] < 75) & (df['S'] == "h") & (df['C'] == "noir"),:]
Out[61]:
T P S F C
6 185 65 h 1 noir
8 174 65 h 3 noir
In [62]:
# meme question mais afficher poids, sexe et couleur des yeux
colonnes = ['P','S','C']
df.loc[(df['P'] < 75) & (df['S'] == "h") & (df['C'] == "noir"),colonnes]
Out[62]:
P S C
6 65 h noir
8 65 h noir
In [63]:
### Croisement des variable
#fréquences selon sexe et couleur des yeux- cela ressemnble à table() de R
#voir : http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.ht ml
pd.crosstab(df['S'],df['C'])
Out[63]:
C bleu brun gris noir vert
S
f 4 8 0 0 3
h 8 15 1 2 4
In [64]:
# meme question en affichant le poutrcentage
pd.crosstab(df['S'],df['C'], normalize='index')
Out[64]:
C bleu brun gris noir vert
S
f 0.266667 0.533333 0.000000 0.000000 0.200000
h 0.266667 0.500000 0.033333 0.066667 0.133333

Matplotlib¶

In [66]:
import matplotlib.pyplot as plt
In [67]:
# Generer 10 nombre compris en 0et 2
x=np.linspace(0,2,10)
x
Out[67]:
array([0.        , 0.22222222, 0.44444444, 0.66666667, 0.88888889,
       1.11111111, 1.33333333, 1.55555556, 1.77777778, 2.        ])
In [68]:
y =x**2
y
Out[68]:
array([0.        , 0.04938272, 0.19753086, 0.44444444, 0.79012346,
       1.2345679 , 1.77777778, 2.41975309, 3.16049383, 4.        ])
In [71]:
plt.plot(x,y)
plt.show()
In [76]:
# Ajouter des parametres
plt.plot(x,y,c='yellow',lw=10,ls='--')
plt.show()
In [77]:
# Modifier la taille du graphique
plt.figure(figsize=(6,6))
plt.plot(x,y,c='black',lw=5,ls='--')
plt.show()
In [78]:
# Plusieurs figures sur un même graphique
z=x**3
plt.plot(x,y)
plt.plot(x,z)
plt.show()
In [79]:
# Ajouter l'etiquettes des axes , un titre et une legende
plt.plot(x,y,label='quadratique')
plt.plot(x,x**3,label='cubique')
plt.title('Figure 5')
plt.xlabel('Axe x')
plt.ylabel('Axe y')
plt.legend()
plt.show()
In [80]:
# Plusieurs graphiques avec subplot

plt.subplot(2,1,1)
plt.plot(x,y,label='quadratique', c='red')
plt.title('Figure 5')
plt.xlabel('Axe x')
plt.ylabel('Axe y')
plt.legend()

plt.subplot(2,1,2)
plt.plot(x,x**3,label='Cubique',c='blue')
plt.xlabel('Axe x')
plt.ylabel('Axe y')
plt.legend()
plt.show()
In [81]:
# Plusieurs graphiques avec subplot

plt.subplot(1,2,1)
plt.plot(x,y,label='quadratique', c='red')
plt.title('Figure 5')
plt.xlabel('Axe x')
plt.ylabel('Axe y')
plt.legend()

plt.subplot(1,2,2)
plt.plot(x,x**3,label='Cubique',c='blue')
plt.xlabel('Axe x')
plt.ylabel('Axe y')
plt.legend()
plt.show()
In [82]:
# Diagramme en batonnet
z = [0,1,2,3,4,5,6,7 ]
t = [8,12,12,7,3,1,1,1]
plt.bar(z,t, width = 0.04, color = 'blue')
plt.title('Diagrammes en baton')
plt.xlabel('Nombre de frere(s)')
plt.ylabel('Effectif')
plt.show()
In [83]:
# Boxplot
box_plot_data=df['F']
plt.boxplot(box_plot_data,labels=['Nombre de frere(s)'])
plt.title('Boxplot')
plt.show()
In [84]:
# Boxplot
box_plot_data=df['F']
plt.boxplot(box_plot_data,patch_artist=True,labels=['Nombre de frere(s)'])
plt.title('Boxplot')
plt.show()
In [85]:
# Histogrammes
y = df['T']
plt.hist(y,5, histtype='bar',align='mid', color='c', label='Taille',edgecolor='black')
plt.title('Histogramme')
plt.legend()
plt.show()
In [86]:
y = df['T']
plt.hist(y,5,align='mid', color='c', label='Taille',edgecolor='black', orientation = 'horizontal')
plt.legend()
plt.ylabel('Taiile')
plt.xlabel('Frequences')
plt.title('Histogramme')
plt.show()
In [87]:
### Barplot simple
haut = [12,23,1,2,7]
bars = ('bleu', 'brun', 'gris', 'noir', 'vert')
# Creer les barres 
plt.bar(bars, haut)
# ajouter des nons a l'axe des abcisses
plt.xticks(bars)
# afficher le graphe
plt.show()
In [88]:
# Pie / camembert
# pie plot simple
plt.figure(figsize = (8, 8))    # agrandir l'affichage
x = [12,23,1,2,7]
plt.pie(x, labels = ['bleu', 'brun', 'gris', 'noir', 'vert'])
plt.legend()
plt.show()
In [89]:
# le scarter plot (nuage de points)
x = df['T']
y = df['P']
plt.scatter(x, y)   
plt.xlabel('Taille')
plt.ylabel('Poids')
plt.title('Nuage de point')
plt.show()
In [90]:
value1 = df[df.S=='h']['T']
value2=df[df.S=='f']['T']

box_plot_data=[value1,value2]
plt.boxplot(box_plot_data, labels=['Homme','Femme'])
plt.title('Boxplot')
plt.show()
In [91]:
## histogrammes supperposés des taiiles par sexe
value1 = df[df.S=='h']['T']
value2=df[df.S=='f']['T']

plt.hist([value1, value2], bins = 5, color = ['yellow', 'green'],
            edgecolor = 'red', hatch = '/', label = ['Homme', '.Femmes'],
            histtype = 'barstacked')
plt.ylabel('valeurs')
plt.xlabel('nombres')
plt.title('2 series superposees')
plt.legend()
plt.show()
In [92]:
value1 = df[df.S=='h']['T']
value2=df[df.S=='f']['T']

box_plot_data=[value1,value2]
plt.boxplot(box_plot_data, labels=['Homme','Femme'])
plt.title('Boxplot')
plt.show()
In [93]:
### Barplot double
data = [[5., 25., 50., 20.],[4., 23., 51., 17.]]
X = np.arange(4)
plt.bar(X + 0.00, data[0], color = 'b', width = 0.25)
plt.bar(X + 0.25, data[1], color = 'g', width = 0.25)
plt.show()
In [ ]: