Vectorized operations

Introduction to NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

A little help from C

 

Graphic of the NumPy and C logos shaking hands

Introduction to NumPy

Vectorized operations

 

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

Speed compared to Python

A graphic of the number three being added to all elements in an array

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 to NumPy

NumPy syntax

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

Multiplying by a scalar

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

Adding two arrays together

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 to NumPy

Multiplying two arrays together

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 to NumPy

Not just for math

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

Vectorize Python code!

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

 

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

Let's practice!

Introduction to NumPy

Preparing Video For Download...