Data Analysis · NumPy Foundations · lesson 2 of 12
Vectorised maths
about 14 minutes · free · runs in your browser
Step 1 of 2
Whole-array arithmetic
Every arithmetic operator works element by element, and two arrays of the same shape combine position by position:
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
a + b # array([11, 22, 33])
b / a # array([10., 10., 10.])
a ** 2 # array([1, 4, 9])
Mixing an array with a single number applies that number to everything — this is called broadcasting:
a * 100 # array([100, 200, 300])
a - 1 # array([0, 1, 2])
NumPy also ships the mathematical functions, and they too work on whole arrays:
np.sqrt, np.round, np.abs, np.exp, np.log.
Your turn: convert an array of Celsius temperatures to Fahrenheit
(F = C * 9/5 + 32), and round the result to one decimal place.
You start from this, and edit it in the browser:
import numpy as np
celsius = np.array([0, 12.5, 21, 30, -8])
# Set fahrenheit, rounded to one decimal place.
Step 2 of 2
Comparing whole arrays
A comparison also applies element by element, and produces an array of booleans:
a = np.array([1, 5, 3, 8])
a > 3 # array([False, True, False, True])
That boolean array is the foundation of the next lesson, but it is already useful on its
own, because True counts as 1:
(a > 3).sum() # 2 — how many are above 3
(a > 3).any() # True
(a > 3).all() # False
Your turn: given daily rainfall, work out how many days were dry (exactly zero), and whether any day exceeded 20mm.
You start from this, and edit it in the browser:
import numpy as np
rain = np.array([0, 4.5, 0, 12, 25.5, 0, 3])
# Set dry_days (an int) and had_downpour (a bool).