Vectorised operations
Element-wise arithmetic
Operators between arrays work element by element:
Python
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** 2)
print(a % 3)Universal functions
NumPy has fast functions that apply to every element:
Python
import numpy as np
x = np.array([1, 4, 9, 16])
print(np.sqrt(x))
print(np.log10(np.array([1, 10, 100, 1000])))
print(np.round(np.array([1.234, 5.678]), 1))
print(np.maximum(np.array([1, 5, 3]), np.array([4, 2, 6])))Indexing and slicing
1D arrays slice like lists; 2D arrays take [row, column]:
Python
import numpy as np
a = np.array([5, 10, 15, 20, 25])
print(a[0], a[-1], a[1:4])
m = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(m[1, 2]) # row 1, column 2 → 6
print(m[0]) # first row
print(m[:, 1]) # second column
print(m[:2, 1:]) # top-right 2x2 blockBoolean masks
A comparison produces an array of True/False, which can filter another array. This is one of NumPy's most powerful ideas:
Python
import numpy as np
scores = np.array([72, 95, 58, 88, 41, 79])
passed = scores >= 60
print(passed)
print(scores[passed]) # keep only passing scores
print(scores[(scores > 60) & (scores < 90)]) # & means "and"
print((scores >= 60).sum(), "students passed")Use & (and), | (or) and ~ (not) between conditions, each in brackets.
Changing values with a mask
Python
import numpy as np
temps = np.array([22, -999, 25, 24, -999, 21]) # -999 means "sensor error"
temps[temps == -999] = 0
print(temps)
clipped = np.where(temps > 23, 23, temps) # cap at 23
print(clipped)np.where(condition, if_true, if_false) builds a new array choosing values element by element.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.