Gevectoriseerde bewerkingen

Introductie tot NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

Een beetje hulp van C

 

Grafiek van de NumPy- en C-logo's die elkaar de hand schudden

Introductie tot NumPy

Gevectoriseerde bewerkingen

 

np.arange(1000000).sum()
499999500000
Introductie tot NumPy

Snelheid vs. Python

Een afbeelding van het getal drie dat bij alle elementen in een array wordt opgeteld

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]])
Introductie tot NumPy

NumPy-syntaxis

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

Vermenigvuldigen met een scalair

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

Twee arrays optellen

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]])
Introductie tot NumPy

Twee arrays vermenigvuldigen

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]])
Introductie tot NumPy

Niet alleen voor wiskunde

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

Python-code vectoriseren!

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

 

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

Laten we oefenen!

Introductie tot NumPy

Preparing Video For Download...