Opérations vectorisées

Introduction à NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

Un coup de pouce de C

 

Graphique des logos NumPy et C se serrant la main

Introduction à NumPy

Opérations vectorisées

 

np.arange(1000000).sum()
499999500000
Introduction à NumPy

Vitesse vs Python

Graphique du nombre trois ajouté à tous les éléments d’un tableau

array = np.array([[1, 2, 3], [4, 5, 6]])
for row in range(array.shape[0]):
    for column in range(array.shape[1]):
        array[row][column] += 3
array([[4, 5, 6],
       [7, 8, 9]])
Introduction à NumPy

Syntaxe NumPy

array = np.array([[1, 2, 3], [4, 5, 6]])
array + 3
array([[4, 5, 6],
       [7, 8, 9]])
Introduction à NumPy

Multiplier par un scalaire

array = np.array([[1, 2, 3], [4, 5, 6]])
array * 3
array([[ 3,  6,  9],
       [12, 15, 18]])
Introduction à NumPy

Addition de deux tableaux

array_a = np.array([[1, 2, 3], [4, 5, 6]])
array_b = np.array([[0, 1, 0], [1, 0, 1]])
array_a + array_b
array([[1, 3, 3],
       [5, 5, 7]])
Introduction à NumPy

Multiplication de deux tableaux

array_a = np.array([[1, 2, 3], [4, 5, 6]])
array_b = np.array([[0, 1, 0], [1, 0, 1]])
array_a * array_b
array([[0, 2, 0],
       [4, 0, 6]])
Introduction à NumPy

Pas seulement pour les maths

array = np.array([[1, 2, 3], [4, 5, 6]])
array > 2
array([[False, False, True],
       [True,  True,  True]])
Introduction à NumPy

Vectoriser du code Python

array = np.array(["NumPy", "is", "awesome"])
len(array) > 2
True

 

vectorized_len = np.vectorize(len)
vectorized_len(array) > 2
array([ True, False,  True])
Introduction à NumPy

Passons à la pratique !

Introduction à NumPy

Preparing Video For Download...