0% ont trouvé ce document utile (0 vote)
16 vues108 pages

1-Numpy Python

Transféré par

boufoussy9
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
16 vues108 pages

1-Numpy Python

Transféré par

boufoussy9
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Python : NumPy

Achref El Mouelhi

Docteur de l’université d’Aix-Marseille


Chercheur en programmation par contrainte (IA)
Ingénieur en génie logiciel

[email protected]

H & H: Research and Training 1 / 72


Plan
1 Introduction
2 Création d’un ndarray
size
ndim et shape
ndmin
3 Types de données
4 Génération de valeurs
arange
reshape
zeros
ones
identity
eye
fromfunction

H & H: Research and Training 2 / 72


Plan

5 Accès aux éléments d’un ndarray

6 Extraction d’un sous-tableau

7 Itération sur un ndarray


for ... in
nditer
ndenumerate

8 Opérations de base sur les ndarray


Opérations arithmétiques
Fonctions universelles
Opérations algébriques

H & H: Research and Training 3 / 72


Introduction

Python
NumPy : Numerical Python

librairie Python dédiée aux tableaux (très utilisés en science de données : Data
Science)

open-source
I c
EL H
créée en 2005 par Travis Oliphant
U
écrite partiellement en Python (lesL MO
écrites en C ou C++)
ref E parties nécessitant des calculs rapides sont

c h
c A

H & H: Research and Training 4 / 72


Introduction

Python
NumPy : Numerical Python

librairie Python dédiée aux tableaux (très utilisés en science de données : Data
Science)

open-source
I c
EL H
créée en 2005 par Travis Oliphant
U
écrite partiellement en Python (lesL MO
écrites en C ou C++)
ref E parties nécessitant des calculs rapides sont

c h
c A
NumPy, pourquoi ?

un accès jusqu’à 50 fois plus rapide que les listes, tuples... de Python : NumPy
stocke les valeurs dans un espace mémoire continu

H & H: Research and Training 4 / 72


Introduction

Python

c
E LHI
Documentation officielle
U
https://numpy.org/
L MO
f E
c hre
c A

H & H: Research and Training 5 / 72


Introduction

Python

Démarche
I c
H
EL espace de travail
Créez un répertoire cours-numpy dans votre
O U
Lancez VSC et allez dans FileM
fE L > Open Folder... et
choisissez cours-numpy
h r e
c créez un fichier main.py
c A
Dans cours-numpy,

H & H: Research and Training 6 / 72


Introduction

Python
Pour installer NumPy, lancez la commande
pip install numpy

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 7 / 72


Introduction

Python
Pour installer NumPy, lancez la commande
pip install numpy

I c
H
ELl’alias np)
U
Pour utiliser NumPy, il faut l’importer (ici sous
import numpy as np
L MO
h r e fE
c
c A

H & H: Research and Training 7 / 72


Introduction

Python
Pour installer NumPy, lancez la commande
pip install numpy

I c
H
ELl’alias np)
U
Pour utiliser NumPy, il faut l’importer (ici sous
import numpy as np
L MO
h r e fE
A c
c
Pour afficher la version de NumPy
import numpy as np

print(np.__version__)
# affiche 1.19.1

H & H: Research and Training 7 / 72


Création d’un ndarray

Python
Pour créer un tableau

import numpy as np

tab = np.array([1, 2, 3, 4, 5])

c
HI
print(tab)
# affiche [1 2 3 4 5]

U E L
L MO
f E
c hre
c A

H & H: Research and Training 8 / 72


Création d’un ndarray

Python
Pour créer un tableau

import numpy as np

tab = np.array([1, 2, 3, 4, 5])

c
HI
print(tab)
# affiche [1 2 3 4 5]

U E L
L MO
f E
Pour déterminer la taille (le nombre d’éléments)

c hre
c A
print(len(tab))
# affiche 5

H & H: Research and Training 8 / 72


Création d’un ndarray

Python
Pour créer un tableau

import numpy as np

tab = np.array([1, 2, 3, 4, 5])

c
HI
print(tab)
# affiche [1 2 3 4 5]

U E L
L MO
f E
Pour déterminer la taille (le nombre d’éléments)

c hre
c A
print(len(tab))
# affiche 5

Pour déterminer le type

print(type(tab))
# affiche <class ’numpy.ndarray’>

H & H: Research and Training 8 / 72


Création d’un ndarray

Python

Explication
I c
EL
ndarray : type de tableau défini par NumPy
H
U
O ètre une liste Python (à
La méthode array() accepteL Mparam
en
r e
plusieurs dimensions)
h fE
ou un tuple et retourne un ndarray.
c
A tableau = nombre d’imbrication
c d’un
Dimension

H & H: Research and Training 9 / 72


Création d’un ndarray size

Python

Pour créer un tableau à deux dimensions

tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 10 / 72


Création d’un ndarray size

Python

Pour créer un tableau à deux dimensions

tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

I c
H
ELle premier tableau
La fonction len retourne le nombre d’éléments : ici 2 car
U
MO
contient deux sous-tableaux

print(len(tab2))
fE L
# affiche 2
c h r e
c A

H & H: Research and Training 10 / 72


Création d’un ndarray size

Python

Pour créer un tableau à deux dimensions

tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

I c
H
ELle premier tableau
La fonction len retourne le nombre d’éléments : ici 2 car
U
MO
contient deux sous-tableaux

print(len(tab2))
fE L
# affiche 2
c h r e
c A
La propriété size retourne le nombre total d’éléments

print (tab2.size)
# affiche 10

H & H: Research and Training 10 / 72


Création d’un ndarray ndim et shape

Python

Pour connaı̂tre le nombre de dimensions, on utilise la propriété


ndim
c
print(tab2.ndim)
# affiche 2
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 11 / 72


Création d’un ndarray ndim et shape

Python

Pour connaı̂tre le nombre de dimensions, on utilise la propriété


ndim
c
print(tab2.ndim)
# affiche 2
E LHI
U
L MO
f E
re un tuple contenant le nombre
d’élémentscpar A
c h
La propriété shape retourne
dimension
print (tab2.shape)
# affiche (2, 5)

H & H: Research and Training 11 / 72


Création d’un ndarray ndim et shape

Python
Pour créer un tableau à trois dimensions (3 nivaux d’imbrications)

tab3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11,


12]]])

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 12 / 72


Création d’un ndarray ndim et shape

Python
Pour créer un tableau à trois dimensions (3 nivaux d’imbrications)

tab3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11,


12]]])

I c
La fonction len retourne le nombre d’éléments : ici 2E
L H
U car le premier tableau
contient deux sous-tableaux
L MO
print(len(tab3))
h r e fE
# affiche 2
c
c A

H & H: Research and Training 12 / 72


Création d’un ndarray ndim et shape

Python
Pour créer un tableau à trois dimensions (3 nivaux d’imbrications)

tab3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11,


12]]])

I c
La fonction len retourne le nombre d’éléments : ici 2E
L H
U car le premier tableau
contient deux sous-tableaux
L MO
print(len(tab3))
h r e fE
# affiche 2
c
c A
Pour connaı̂tre le nombre de dimensions, on utilise ndim

print(tab3.ndim)
# affiche 3

H & H: Research and Training 12 / 72


Création d’un ndarray ndim et shape

Python
Attention, le tableau suivant a 3 éléments et 2 dimensions
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(len(array))
c
# affiche 3
E LHI
U
MO
print(array.ndim)
# affiche 2
f E L
c hre
c A

H & H: Research and Training 13 / 72


Création d’un ndarray ndim et shape

Python
Attention, le tableau suivant a 3 éléments et 2 dimensions
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(len(array))
c
# affiche 3
E LHI
U
MO
print(array.ndim)
# affiche 2
f E L
A c hre
c
Pour créer un ndarray à partir d’un tuple
tup = np.array((1, 2, 3))

print(len(tup))
# affiche 3

H & H: Research and Training 13 / 72


Création d’un ndarray ndim et shape

Python

I c
Remarques
EL H
O U
Un ndarray contenant un seul élément (np.array(4) par
exemple) est de dimension 0L M
Chaque élémenth r e fE
c d’un ndarray est de dimension 0
c A

H & H: Research and Training 14 / 72


Création d’un ndarray ndmin

Python

Pour créer un tableau à 4 dimensions, on peut faire


c
tab4 = np.array([1, 2, 3, 4], ndmin=4)
E LHI
U
print(tab4)
L MO
# affiche [[[1 2 3 4]]]
f E
c hre
print(tab4.ndim)
# affiche 4 c A

H & H: Research and Training 15 / 72


Types de données

Python
Types de données autorisés par NumPy

i - integer

b - boolean

c
u - unsigned integer

E LHI
f - float
U
c - complex float
L MO
f E
hre
m - timedelta
c
M - datetime

O - object
c A
S - string : chaı̂ne + codage (utf-8 par exemple)

U - unicode string : chaı̂ne non-codée

...

H & H: Research and Training 16 / 72


Types de données

Python

Pour connaitre le type d’un tableau, on utilise la propriété dtype


tab = np.array([1, 2, 3, 4, 5])

c
print(tab.dtype)
# affiche int32 (32 bits = 4 octets)
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 17 / 72


Types de données

Python

Pour connaitre le type d’un tableau, on utilise la propriété dtype


tab = np.array([1, 2, 3, 4, 5])

c
print(tab.dtype)
# affiche int32 (32 bits = 4 octets)
E LHI
U
L MO
f E
red’octets
c h
Pour préciser le nombre
c A 2, 3, 4, 5], dtype=’i8’)
tab = np.array([1,
print(tab.dtype)

# affiche int64

H & H: Research and Training 17 / 72


Types de données

On peut aussi choisir un autre type


tab = np.array([1, 2, 3, 4, 5], dtype=’S’)

print(tab.dtype)
# affiche |S1

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 18 / 72


Types de données

On peut aussi choisir un autre type


tab = np.array([1, 2, 3, 4, 5], dtype=’S’)

print(tab.dtype)
# affiche |S1

c
Ou en utilisant la méthode astype

E LHI
tab = np.array([1, 2, 3, 4, 5])
U
MO
strings = tab.astype(’S’)

print(strings.dtype)
f E L
# affiche |S11
c hre
c A

H & H: Research and Training 18 / 72


Types de données

On peut aussi choisir un autre type


tab = np.array([1, 2, 3, 4, 5], dtype=’S’)

print(tab.dtype)
# affiche |S1

c
Ou en utilisant la méthode astype

E LHI
tab = np.array([1, 2, 3, 4, 5])
U
MO
strings = tab.astype(’S’)

print(strings.dtype)
f E L
# affiche |S11
c hre
c A
Ou
tab = np.array([1, 2, 3, 4, 5])
strings = tab.astype(str)

print(strings.dtype)
# affiche |U11

H & H: Research and Training 18 / 72


Types de données

Python

I c
Remarques
H
L être convertie.
Epeut
O
Une exception sera levée si une valeurUne
L M
r e Epeut préciser la taille sont i, u, f, S et
Les types pour lesquelsf on
U.
A ch
c

H & H: Research and Training 19 / 72


Génération de valeurs arange

Pour générer 15 valeurs incrémentales pour un tableau à une dimension

t = np.arange(15)

print(t)
# affiche [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 20 / 72


Génération de valeurs arange

Pour générer 15 valeurs incrémentales pour un tableau à une dimension

t = np.arange(15)

print(t)
# affiche [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

c
arange([start, ]stop, [step, ]dtype=None)
E LHI
U
Valeur par défaut pour start est 0
L MO
f E
hre
Valeur par défaut pour step est 1

c
c A

H & H: Research and Training 20 / 72


Génération de valeurs arange

Pour générer 15 valeurs incrémentales pour un tableau à une dimension

t = np.arange(15)

print(t)
# affiche [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

c
arange([start, ]stop, [step, ]dtype=None)
E LHI
U
Valeur par défaut pour start est 0
L MO
f E
hre
Valeur par défaut pour step est 1

c
c A
Pour générer 15 valeurs incrémentales commençant de 1

t = np.arange(1, 16, 1)

print(t)
# affiche [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]

H & H: Research and Training 20 / 72


Génération de valeurs reshape

Pour générer 15 valeurs incrémentales pour un tableau à plusieurs dimensions (ici 2)


t2 = np.arange(1, 16, 1).reshape(3, 5)

print(t2)
# affiche [[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15]]

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 21 / 72


Génération de valeurs reshape

Pour générer 15 valeurs incrémentales pour un tableau à plusieurs dimensions (ici 2)


t2 = np.arange(1, 16, 1).reshape(3, 5)

print(t2)
# affiche [[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15]]

c
HI
Pour générer 12 valeurs incrémentales pour un tableau à trois dimensions
t3 = np.arange(1, 13, 1).reshape(3, 2, 2)
U E L
print(t3)
L MO
# affiche [[[ 1 2] [ 3
f E
4]] [[ 5 6] [ 7 8]] [[ 9 10] [11 12]]]

c hre
c A

H & H: Research and Training 21 / 72


Génération de valeurs reshape

Pour générer 15 valeurs incrémentales pour un tableau à plusieurs dimensions (ici 2)


t2 = np.arange(1, 16, 1).reshape(3, 5)

print(t2)
# affiche [[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15]]

c
HI
Pour générer 12 valeurs incrémentales pour un tableau à trois dimensions
t3 = np.arange(1, 13, 1).reshape(3, 2, 2)
U E L
print(t3)
L MO
# affiche [[[ 1 2] [ 3
f E
4]] [[ 5 6] [ 7 8]] [[ 9 10] [11 12]]]

c hre
c A
Si les valeurs passées pour les paramètres ne permettent pas de créer le tableau, une
exception sera levée
t3 = np.arange(1, 13, 1).reshape(3, 2, 3)

print(t3)
# affiche ValueError: cannot reshape array of size 12 into shape
(3,2,3)

H & H: Research and Training 21 / 72


Génération de valeurs reshape

Python
La méthode reshape() accepte aussi comme paramètre un tableau de
dimension différente

t = np.arange(1, 13, 1)
t3 = t.reshape(3, 2, -1)

I c
print(t3)
# affiche [[[ 1 H
EL [[ 9 10] [11
2] [ 3 4]] [[ 5 6] [ 7 8]]
U
MO
12]]]

fE L
h r e
c Ac

H & H: Research and Training 22 / 72


Génération de valeurs reshape

Python
La méthode reshape() accepte aussi comme paramètre un tableau de
dimension différente

t = np.arange(1, 13, 1)
t3 = t.reshape(3, 2, -1)

I c
print(t3)
# affiche [[[ 1 H
EL [[ 9 10] [11
2] [ 3 4]] [[ 5 6] [ 7 8]]
U
MO
12]]]

fE L
c h r e
c A la valeur -1 (une seule fois) pour que NumPy calcule le
On peut aussi utiliser
nombre manquant

t3 = np.arange(1, 13, 1).reshape(3, 2, -1)

print(t3)
# affiche [[[ 1 2] [ 3 4]] [[ 5 6] [ 7 8]] [[ 9 10] [11
12]]]

H & H: Research and Training 22 / 72


Génération de valeurs reshape

Python

reshape(-1) permet de convertir un tableau quelle que soit sa


I c
dimension en un tableau d’une seule dimension
EL H
O U
t3 = np.arange(1, 13, 1).reshape(3, 2, -1)
t = t3.reshape(-1)
L M
ref E
print(t) c h
# affichec [A1 2 3 4 5 6 7 8 9 10 11 12]

H & H: Research and Training 23 / 72


Génération de valeurs zeros

Python
Pour créer un tableau et l’initialiser avec des zéros (réels)
zeros = np.zeros(3)

print(zeros)
# affiche [ 0. 0. 0.]
c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 24 / 72


Génération de valeurs zeros

Python
Pour créer un tableau et l’initialiser avec des zéros (réels)
zeros = np.zeros(3)

print(zeros)
# affiche [ 0. 0. 0.]
c
E LHI
U
Pour créer un tableau et l’initialiser avec des zéros (entiers)
zeros = np.zeros(3, dtype=np.int32)
L MO
f E
print(zeros)
c hre
c A
# affiche [ 0 0 0]

H & H: Research and Training 24 / 72


Génération de valeurs zeros

Python
Pour créer un tableau et l’initialiser avec des zéros (réels)
zeros = np.zeros(3)

print(zeros)
# affiche [ 0. 0. 0.]
c
E LHI
U
Pour créer un tableau et l’initialiser avec des zéros (entiers)
zeros = np.zeros(3, dtype=np.int32)
L MO
f E
print(zeros)
c hre
c A
# affiche [ 0 0 0]

Pour créer un tableau de zéros à deux dimensions (ou plus)


zeros = np.zeros((3,2), dtype=np.int32)

print(zeros)
# affiche [[0 0] [0 0] [0 0]]

H & H: Research and Training 24 / 72


Génération de valeurs ones

Python

c
ones
E LHI
OU
fonctionne exactement comme zeros
M
retourne un tableau def1 E
L
c h re
c A

H & H: Research and Training 25 / 72


Génération de valeurs identity

Python

Pour généré un tableau identité (au sens matrice carrée)


c
HI
iden = np.identity(2)

U E L
MO
print(iden)
# affiche
f E L
hre
# [
c
c A
# [1. 0.]
# [0. 1.]
# ]

H & H: Research and Training 26 / 72


Génération de valeurs eye

Python

identity est un cas particulier de eye


c
HI
oeil = np.eye(2)

U E L
MO
print(oeil)
# affiche
f E L
hre
# [
c
c A
# [1. 0.]
# [0. 1.]
# ]

H & H: Research and Training 27 / 72


Génération de valeurs eye

Python

eye permet de générer aussi des matrices non-carrées


c
HI
oeil = np.eye(2, 3)

U E L
MO
print(oeil)
# affiche
f E L
hre
# [
c
c A
# [1. 0. 0.]
# [0. 1. 0.]
# ]

H & H: Research and Training 28 / 72


Génération de valeurs eye

Python

eye permet aussi de faire une translation de la diagonale


oeil = np.eye(3, 3, 1)
c
E LHI
print(oeil)
U
# affiche
L MO
# [
f E
# [0. 1. 0.]
c hre
# [0. 0. 1.]
# [0. 0. 0.]
c A
# ]

H & H: Research and Training 29 / 72


Génération de valeurs fromfunction

Python

Pour générer les valeurs d’un tableau à partir d’une fonction lambda
fonction = np.fromfunction(lambda i, j: i + j, (3, 2)) c
E LHI
print(fonction)
U
# affiche
L MO
# [
f E
# [0. 1.]
c hre
c A
# [1. 2.]
# [2. 3.]
# ]

H & H: Research and Training 30 / 72


Accès aux éléments d’un ndarray

Pour accéder au premier élément d’un tableau d’une dimension

tab = np.array([1, 2, 3, 4, 5])

print(tab[0])
# affiche 1

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 31 / 72


Accès aux éléments d’un ndarray

Pour accéder au premier élément d’un tableau d’une dimension

tab = np.array([1, 2, 3, 4, 5])

print(tab[0])
# affiche 1

c
dimensions
E LHI
Pour accéder au deuxième élément de la deuxième dimension d’un tableau à deux

U
tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
L MO
f E
hre
print(tab2[0, 1])
# affiche 2
c
c A

H & H: Research and Training 31 / 72


Accès aux éléments d’un ndarray

Pour accéder au premier élément d’un tableau d’une dimension

tab = np.array([1, 2, 3, 4, 5])

print(tab[0])
# affiche 1

c
dimensions
E LHI
Pour accéder au deuxième élément de la deuxième dimension d’un tableau à deux

U
tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
L MO
f E
hre
print(tab2[0, 1])
# affiche 2
c
c A
Pour accéder au deuxième élément du premier tableau défini dans le deuxième tableau

tab3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(tab3[1, 0, 1])
# affiche 8

H & H: Research and Training 31 / 72


Accès aux éléments d’un ndarray

Python

Exemples avec des valeurs négatives

tab = np.array([1, 2, 3, 4, 5])

print(tab[-1])
I c
# affiche 5
EL H
O U
tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
L M
print(tab2[-1, -3])
h r e fE
# affiche 8
A c
c
tab3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11,
12]]])

print(tab3[1, 0, -2])
# affiche 8

H & H: Research and Training 32 / 72


Extraction d’un sous-tableau

Python

Démarche
c
HI
Pour extraire un sous tableau, on utilise l’opérateur
[deb:fin:pas] ou [deb:fin]
U E L
deb, fin et pas sont optionnelsMO
EL
defdeb est 0
La valeur par défautre
A c h
c par défaut de fin est la taille du tableau
La valeur
La valeur par défaut de pas est 1

H & H: Research and Training 33 / 72


Extraction d’un sous-tableau

Python
Exemples

tab = np.array([1, 2, 3, 4, 5])

print(tab[1])
c
# affiche 2

E LHI
U
MO
print(tab[1:])
# affiche [2 3 4 5]

f E L
print(tab[1:4])
Ac
# affiche [2 3 4] hre
c
print(tab[1:4:2])
# affiche [2 4]

print(tab[1::2])
# affiche [2 4]

H & H: Research and Training 34 / 72


Extraction d’un sous-tableau

Python
Exemples avec un tableau à deux dimensions

tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(tab2[0:2, 2:5])
c
# affiche [[ 3 4 5] [ 8 9 10]]

E LHI
U
MO
print(tab2[0:2, 2])
# affiche [3 8]

f E L
print(tab2[1, 2:5])
Ac
# affiche [ 8 9 10] hre
c
print(tab2[0:2, 2:5:2])
# affiche [[ 3 5] [ 8 10]]

print(tab2[0:1, 1::2])
# affiche [[2 4]]

H & H: Research and Training 35 / 72


Itération sur un ndarray for ... in

Python

Pour itérer sur un tableau à une dimension


tab = np.array([1, 2, 3, 4, 5])
c
for elt in tab:
E LHI
print(elt) U
L MO
f E
hre
# affiche
# 1 c
#
#
2
3
c A
# 4
# 5

H & H: Research and Training 36 / 72


Itération sur un ndarray for ... in

Python

Itérer sur un tableau à deux dimensions avec une seule boucle


affiche
c
tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
E LHI
U
for elt in tab2:
L MO
print(elt)
f E
c hre
# affiche
# [1 2 3 4 5]
c A
# [ 6 7 8 9 10]

H & H: Research and Training 37 / 72


Itération sur un ndarray for ... in

Python
Pour accéder à tous les éléments

tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

for elt in tab2:


c
HI
for sub_elt in elt:
print(sub_elt)

U E L
# affiche
L MO
# 1
f E
hre
# 2
# 3
c
#
#
4
5 c A
# 6
# 7
# 8
# 9
# 10

H & H: Research and Training 38 / 72


Itération sur un ndarray for ... in

Python
Par analogie, pour un tableau à 3 dimensions, il faut 3 boucles for

tab3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

for x in tab3:
for y in x:
c
HI
for z in y:
print(z)

U E L
MO
# affiche
#
#
1
2
f E L
# 3
c hre
c A
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 11
# 12

H & H: Research and Training 39 / 72


Itération sur un ndarray nditer

Python
NumPy nous offre une syntaxe plus simple pour simplifier le code précédent quelle que
soit la dimension du tableau

tab3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

for x in np.nditer(tab3):
c
print(x)

E LHI
# affiche
U
# 1
L MO
# 2
f E
hre
# 3
# 4
c
c A
# 5
# 6
# 7
# 8
# 9
# 10
# 11
# 12

H & H: Research and Training 40 / 72


Itération sur un ndarray ndenumerate

Python

Pour avoir l’indice ainsi que la valeur, on utilise ndenumerate


tab = np.array([1, 2, 3, 4, 5])
c
for index, elt in np.ndenumerate(tab):
E LHI
print(index, elt) U
L MO
f E
hre
# affiche
# (0,) 1 c
#
#
(1,) 2
(2,) 3
c A
# (3,) 4
# (4,) 5

H & H: Research and Training 41 / 72


Itération sur un ndarray ndenumerate

Python
Exemple avec un tableau à deux dimensions

tab2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

for index, elt in np.ndenumerate(tab2):


c
print(index, elt)

E LHI
U
MO
# affiche
# (0, 0) 1
# (0, 1) 2
f E L
# (0, 2) 3
c hre
c A
# (0, 3) 4
# (0, 4) 5
# (1, 0) 6
# (1, 1) 7
# (1, 2) 8
# (1, 3) 9
# (1, 4) 10

H & H: Research and Training 42 / 72


Opérations de base sur les ndarray Opérations arithmétiques

Python
Considérons les deux tableaux (à une dimension) suivants

a = np.arange(1, 6)
b = np.arange(1, 10, 2)

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 43 / 72


Opérations de base sur les ndarray Opérations arithmétiques

Python
Considérons les deux tableaux (à une dimension) suivants

a = np.arange(1, 6)
b = np.arange(1, 10, 2)

Il est possible d’effectuer les opérations arithmétiques suivantes

r = a + b
c
HI
print(a, b, r)
# affiche [1 2 3 4 5] [1 3 5 7 9] [ 2 5 8 11 14]

U E L
MO
r = a - b
print(a, b, r)

f E L
# affiche [1 2 3 4 5] [1 3 5 7 9] [ 0 -1 -2 -3 -4]

hre
r = a * b
print(a, b, r)

c
c A
# affiche [1 2 3 4 5] [1 3 5 7 9] [ 1 6 15 28 45]

r = a / b
print(a, b, r)
# affiche [1 2 3 4 5] [1 3 5 7 9] [1. 0.66666667 0.6 0.57142857 0.55555556]

r = a * 2
print(a, r)
# affiche [1 2 3 4 5] [ 2 4 6 8 10]

r = a ** 2
print(a, r)
# affiche 1 2 3 4 5] [ 1 4 9 16 25]

H & H: Research and Training 43 / 72


Opérations de base sur les ndarray Opérations arithmétiques

Python

Les opérateurs suivants sont également applicables


c
a += 2
print(a) E LHI
U
# affiche [3 4 5 6 7]
L MO
f E
a *= 2
c hre
print(a)
# affiche [ 6 c A 8 10 12 14]

H & H: Research and Training 44 / 72


Opérations de base sur les ndarray Opérations arithmétiques

Attention pour les tableaux à deux dimensions ou plus, le produit ne correspond pas au
produit de deux matrices
a2 = np.arange(1,5).reshape(2, 2)
b2 = np.arange(3,7).reshape(2, 2)

print (a2)
# affiche [[1 2] [3 4]]

c
HI
print (b2)
# affiche [[3 4] [5 6]]

U E L
print (a2 * b2)
# affiche [[ 3 8] [15 24]]
L MO
f E
c hre
c A

H & H: Research and Training 45 / 72


Opérations de base sur les ndarray Opérations arithmétiques

Attention pour les tableaux à deux dimensions ou plus, le produit ne correspond pas au
produit de deux matrices
a2 = np.arange(1,5).reshape(2, 2)
b2 = np.arange(3,7).reshape(2, 2)

print (a2)
# affiche [[1 2] [3 4]]

c
HI
print (b2)
# affiche [[3 4] [5 6]]

U E L
print (a2 * b2)
# affiche [[ 3 8] [15 24]]
L MO
f E
c hre
c A
Pour faire le produit de deux matrices, on utilise l’opérateur @ (valable depuis Python 3.5)
print (a2)
# affiche [[1 2] [3 4]]

print (b2)
# affiche [[3 4] [5 6]]

print (a2 @ b2)


# affiche [[13 16] [29 36]]

H & H: Research and Training 45 / 72


Opérations de base sur les ndarray Opérations arithmétiques

Python

Ou en appelant la méthode dot()


c
HI
print (a2)
# affiche [[1 2] [3 4]]
U E L
print (b2)
L MO
f E
hre
# affiche [[3 4] [5 6]]
c
print (a2.dot(b2)) c A
# affiche [[13 16] [29 36]]

H & H: Research and Training 46 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

c
HI
Il est possible d’appliquer une fonction sur tous les éléments
d’un tableau
U E L
print(np.sqrt((a)))
L MO
# affiche [1.
f E
1.41421356 1.73205081 2.
2.23606798]
c hre
c A

H & H: Research and Training 47 / 72


Opérations de base sur les ndarray Fonctions universelles

Python
Autres fonctions

exp : retourne un tableau d’exponentielle

average : retourne la moyenne de tous les éléments d’un tableau

c
HI
sum : retourne la somme de tous les éléments d’un tableau

prod : retourne le produit de tous les éléments d’un tableau

U E L
MO
diff : retourne le tableau de différence entre chaque élément et son successeur

L
max : retourne le max d’un tableau
f E
c hre
maximum : retourne un tableau de tous les max en comparant les éléments ayant le même indice

c A
all : vérifie si tous les éléments d’un tableau respectent une condition

any : vérifie s’il existe un élément d’un tableau respectant une condition

where : retourne un tableau transformé selon la condition indiquée

sort : retourne un tableau trié quel que soit le type de ses données

...

H & H: Research and Training 48 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

Pour récupérer les indices des éléments pairs


c
HI
print(np.where(a % 2 == 0))
# affiche (array([1, 3], dtype=int32),)
U E L
L MO
f E
c hre
c A

H & H: Research and Training 49 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

Pour récupérer les indices des éléments pairs


c
HI
print(np.where(a % 2 == 0))
# affiche (array([1, 3], dtype=int32),)
U E L
L MO
f E
re pairs par 2 et les impairs par 3
h
Pour multiplier les éléments
c
c A % 2 == 0, a * 2, a * 3))
print(np.where(a
# affiche [ 3 4 9 8 15]

H & H: Research and Training 49 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

Pour récupérer le max d’un tableau)


print(np.max(a))
c
# affiche 5
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 50 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

Pour récupérer le max d’un tableau)


print(np.max(a))
c
# affiche 5
E LHI
U
L MO
f E
hre
Pour récupérer le max de chaque couple d’éléments ayant le
Ac
même indice de deux tableaux différents
c
print(np.maximum(a, b))
# affiche [1 3 5 7 9]

H & H: Research and Training 50 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

Pour vérifie si tous les éléments d’un tableau vérifient une condition

print(np.all(a % 2 == 0))
# affiche False

c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 51 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

Pour vérifie si tous les éléments d’un tableau vérifient une condition

print(np.all(a % 2 == 0))
# affiche False

c
E LHI
U
MO
Pour vérifie s’il existe un élément du tableau vérifient une condition

print(np.any(a % 2 == 0))
f E L
hre
# affiche True

c
c A

H & H: Research and Training 51 / 72


Opérations de base sur les ndarray Fonctions universelles

Python

Pour vérifie si tous les éléments d’un tableau vérifient une condition

print(np.all(a % 2 == 0))
# affiche False

c
E LHI
U
MO
Pour vérifie s’il existe un élément du tableau vérifient une condition

print(np.any(a % 2 == 0))
f E L
hre
# affiche True

c
c A
Pour retourner le tableau de différence entre chaque élément et son successeur

print(np.diff(b))
# affiche [2 2 2 2]

H & H: Research and Training 51 / 72


Opérations de base sur les ndarray Opérations algébriques

Python
Considérons la matrice suivante

a2 = np.arange(1,5).reshape(2, 2)

print (a2)
# affiche [[1 2] [3 4]]
c
E LHI
U
L MO
f E
c hre
c A

H & H: Research and Training 52 / 72


Opérations de base sur les ndarray Opérations algébriques

Python
Considérons la matrice suivante

a2 = np.arange(1,5).reshape(2, 2)

print (a2)
# affiche [[1 2] [3 4]]
c
E LHI
U
Pour déterminer le transposé de a2
L MO
f E
print (a2.transpose())
c hre
c A
# affiche [[1 3] [2 4]]

H & H: Research and Training 52 / 72


Opérations de base sur les ndarray Opérations algébriques

Python
Considérons la matrice suivante

a2 = np.arange(1,5).reshape(2, 2)

print (a2)
# affiche [[1 2] [3 4]]
c
E LHI
U
Pour déterminer le transposé de a2
L MO
f E
print (a2.transpose())
c hre
c A
# affiche [[1 3] [2 4]]

Pour calculer la trace de a2

print (a2.trace())
# affiche 5

H & H: Research and Training 52 / 72


Affectation, copie et vue

Python

Explication
I c
H
Affectation : permet d’avoir un deuxième nom pour le même
EL
tableau
U
Vue : permet de créer un deuxiL MO
ème tableau dont les valeurs
re
pointent sur les mêmes f E
valeurs du tableau précédent
c h
A de créer un tableau avec un espace mémoire
Copie :c permet
différent pour les valeurs

H & H: Research and Training 53 / 72


Affectation, copie et vue Affectation

Python

Exemple avec l’affectation


a = np.arange(1, 4)

b = a c
E LHI
b[2] = 10
U
L MO
print(a)
f E
# affiche [ 1
c hre
2 10]

print(b is a) c A
# affiche True

print(id(a), id(b))
# affiche 58092304 58092304

H & H: Research and Training 54 / 72


Affectation, copie et vue Vue

Python

Exemple avec view()


a = np.arange(1, 4)

c = a.view() c
E LHI
c[2] = 10
U
L MO
print(a)
f E
# affiche [ 1
c hre
2 10]

print(c is a) c A
# affiche False

print(id(a), id(c))
# affiche 51800928 51801488

H & H: Research and Training 55 / 72


Affectation, copie et vue Vue

Python

c
E LHI
U
L MO
f E
c hre
c A

(Image de StackOverFlow)
H & H: Research and Training 56 / 72
Affectation, copie et vue Copie

Python

Exemple avec copie()


a = np.arange(1, 4)

d = a.copy() c
E LHI
d[2] = 10
U
L MO
print(a)
f E
# affidhe [ 1
c hre
2 3]

print(d is a) c A
# affidhe False

print(id(a), id(d))
# affidhe 17984272 17984832

H & H: Research and Training 57 / 72


Fusion de ndarray

Python

Considérons les deux tableaux (à deux dimensions) suivants


m1 = np.arange(1, 5).reshape(2, 2)
c
E LHI
print(m1)
U
# affiche [[1 2] [3 4]]
L MO
e f E
r9).reshape(2,
c h
m2 = np.arange(5, 2)

print(m2)
c A
# affiche [[5 6] [7 8]]

H & H: Research and Training 58 / 72


Fusion de ndarray concatenate

Python
Pour fusionner les deux tableaux et obtenir un tableau à deux
dimensions contenant les éléments du premier tableau ensuite le
second
m = np.concatenate((m1, m2))
c
E LHI
OU
print(m)

L M
# affiche [[1 2] [3 4] [5 6] [7 8]]

h r e fE
c
c A

H & H: Research and Training 59 / 72


Fusion de ndarray concatenate

Python
Pour fusionner les deux tableaux et obtenir un tableau à deux
dimensions contenant les éléments du premier tableau ensuite le
second
m = np.concatenate((m1, m2))
c
E L HI
OU
print(m)
# affiche [[1 2] [3 4] [5 6]
L M [7 8]]

h r e fE
Acest un raccourci du code suivant
cédent
Le code préc
m = np.concatenate((m1, m2), axis=0)

print(m)
# affiche [[1 2] [3 4] [5 6] [7 8]]

H & H: Research and Training 59 / 72


Fusion de ndarray concatenate

Python

Pour fusionner les éléments de même indice ensemble


m = np.concatenate((m1, m2), axis=1)

c
print(m)
[3 4 7 8]] EL
HI
OU
# affiche [[1 2 5 6]
M
h re f EL
A c
c

H & H: Research and Training 60 / 72


Fusion de ndarray concatenate

Python

Pour fusionner les éléments de même indice ensemble


m = np.concatenate((m1, m2), axis=1)

c
print(m)
[3 4 7 8]] EL
HI
OU
# affiche [[1 2 5 6]
M
h re f EL
c
Pour fusionner et obtenir un tableau à une seule dimension
A
c
m = np.concatenate((m1, m2), axis=None)

print(m)
# affiche [1 2 3 4 5 6 7 8]

H & H: Research and Training 60 / 72


Fusion de ndarray stack

Python

Pour tout fusionner dans un nouveau tableau (de dimension 3)


m = np.stack((m1, m2), axis=0)

c
HI
print(m)
# affiche [[[1 2] [3 4]] [[5 6] [7 8]]]
U E L
L MO
f E
c hre
c A

H & H: Research and Training 61 / 72


Fusion de ndarray stack

Python

Pour tout fusionner dans un nouveau tableau (de dimension 3)


m = np.stack((m1, m2), axis=0)

c
HI
print(m)
# affiche [[[1 2] [3 4]] [[5 6] [7 8]]]
U E L
L MO
f E
re de de même indice dans un tableau
h
Pour fusionner les éléments
c
ensemble
c A
m = np.stack((m1, m2), axis=1)

print(m)
# affiche [[[1 2] [5 6]] [[3 4] [7 8]]]

H & H: Research and Training 61 / 72


Fusion de ndarray hstack

Python

Pour fusionner (horizontalement) les éléments de même indicec


ensemble (comme concatenate avec axis=1)
E LHI
U
m = np.hstack((m1, m2))
L MO
f E
print(m)
c hre
c A
# affiche [[1 2 5 6] [3 4 7 8]]

H & H: Research and Training 62 / 72


Fusion de ndarray vstack

Python

Pour fusionner (verticalement) tous les éléments dans un seulc


tableau (comme concatenate avec axis=0)
E LHI
U
m = np.vstack((m1, m2))
L MO
f E
print(m)
c hre
c A
# affiche [[1 2] [3 4] [5 6] [7 8]]

H & H: Research and Training 63 / 72


Fusion de ndarray dstack

Python

c
HI
Pour fusionner selon la profondeur
m = np.dstack((m1, m2))
U E L
L MO
print(m)
f E
c hre
# affiche [[[1 5] [2 6]] [[3 7] [4 8]]]
c A

H & H: Research and Training 64 / 72


Fusion de ndarray block

Python

c
HI
Pour construire un nouveau tableau par bloc
m = np.block([m1, m2])
U E L
L MO
print(m)
f E
c hre
# affiche [[1 2 5 6] [3 4 7 8]]
c A

H & H: Research and Training 65 / 72


Fusion de ndarray block

Python
Ou sous forme d’un tableau à plusieurs dimensions
m = np.block(
[
[m1, np.zeros((2, 2), dtype=np.int32)],
c
[np.ones(4, dtype=np.int32)],
E LHI
[np.zeros((2, 2), dtype=np.int32), m2]
U
]
L MO
)
f E
c hre
print(m)
# affiche
c[[1A2 0 0]
# [3 4 0 0]
# [1 1 1 1]
# [0 0 5 6]
# [0 0 7 8]]

H & H: Research and Training 66 / 72


Décomposition array split

Python
Pour décomposer un tableau en plusieurs sous-tableaux, on peut
utiliser la méthode array split
t = np.arange(1, 11)

c
print (np.array_split(t, 2))
# affiche [
E LHI
U
#
#
array([1, 2, 3, 4, 5]),
array([ 6, 7, 8, 9, 10])
L MO
f E
hre
# ]
c
c A
print (np.array_split(t, 3))
# affiche [
# array([1, 2, 3, 4]),
# array([5, 6, 7]),
# array([ 8, 9, 10])
# ]

H & H: Research and Training 67 / 72


Décomposition array split

Python

Exemple avec un tableau à deux dimensions

t2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14,
15], [16, 17, 18]])
c
print(np.array_split(t2, 3))
E LHI
# affiche [array([[1, 2, 3],
U
MO
# [4, 5, 6]]), array([[ 7, 8, 9],
#
# [16, 17, 18]])]
f E L
[10, 11, 12]]), array([[13, 14, 15],

c hre
c A
print(np.array_split(t2, 2))
# affiche [array([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]), array([[10, 11, 12],
# [13, 14, 15],
# [16, 17, 18]])]

H & H: Research and Training 68 / 72


Décomposition split

Python

On peut aussi utiliser la méthode split qui lève une exception si la


taille du tableau n’est pas divisible par le paramètre
t = np.arange(1, 11)
c
E LHI
print (np.array_split(t, 2))
O U
# affiche [
L M
#
# array([ 6, 7, e8,
r E
array([1, 2, 3, 4, 5]),
f 9, 10])
# ]
A c h
c
print (np.array_split(t, 3))
# affiche ValueError: array split does not result in an
equal division

H & H: Research and Training 69 / 72


Décomposition split

Python

I c
Remarque
E LH
U
MOhstack,vstack et dstack
Comme pour stack et ses variantes
L
r e f Eet dsplit
Il existe hsplit, vsplit
h
c
c A

H & H: Research and Training 70 / 72


Filtres

Python

Pour filtrer les éléments impairs, on peut utiliser where (qui


retourne un tableau d’indices)
tab = np.array([1, 2, 3, 4, 5])
c
print(np.where(tab % 2 != 0))
E LHI
U
MO
# (array([0, 2, 4], dtype=int32),)

f E L
c hre
c A

H & H: Research and Training 71 / 72


Filtres

Python

Pour filtrer les éléments impairs, on peut utiliser where (qui


retourne un tableau d’indices)
tab = np.array([1, 2, 3, 4, 5])
c
print(np.where(tab % 2 != 0))
E LHI
U
MO
# (array([0, 2, 4], dtype=int32),)

f E L
c hre
c A
Si on a besoin de valeurs, on peut définir un tableau de booléens
filtre = [True, False, True, False, True]

print(tab[filtre])
# affiche [1 3 5]

H & H: Research and Training 71 / 72


Filtres

Python
On peut aussi utiliser where pour construire le filtre (tableau de
booléens)
filtre = np.where(tab % 2 != 0, True, False)
c
print(tab[filtre])
E LHI
# affiche [1 3 5]
U
# (array([0, 2, 4], dtype=int32),)
L MO
f E
c hre
c A

H & H: Research and Training 72 / 72


Filtres

Python
On peut aussi utiliser where pour construire le filtre (tableau de
booléens)
filtre = np.where(tab % 2 != 0, True, False)
c
print(tab[filtre])
E LHI
# affiche [1 3 5]
U
# (array([0, 2, 4], dtype=int32),)
L MO
f E
c hre
Ou sans le where c A
filtre = tab % 2 != 0

print(tab[filtre])
# affiche [1 3 5]

H & H: Research and Training 72 / 72

Vous aimerez peut-être aussi