Masks and filtering
import numpy as np a = np.array([12, 45, 7, 60, 33]) mask = a > 20 print(mask) print(a[mask]) print(a[a % 2 == 0])
Write Python. Understand every error.
NumPy · topic 22 of 25
Comparing an array with a value gives an array of True and False, one for each element. This is called a boolean mask.
a = np.array([12, 45, 7, 60]) print(a > 20) # [False True False True] print(a[a > 20]) # [45 60]
Putting a mask inside square brackets keeps only the elements where the mask is True. This replaces a loop with an if inside it.
To combine conditions, use & for "and", | for "or" and ~ for "not", and put brackets around each condition: a[(a > 10) & (a < 50)]. The words and and or do not work on arrays and cause an error.
Because True counts as 1, mask.sum() or np.count_nonzero(mask) counts matching elements, and mask.mean() gives the fraction that match.
np.where(condition, x, y) builds a new array, taking x where the condition holds and y elsewhere. A mask can also be used on the left of = to change only some elements: a[a < 0] = 0.
True and False, called a boolean mask.True.&, | and ~, and put brackets around each condition.mask.sum() counts the matches, and np.where(condition, x, y) chooses between two values.and or or on arrays instead of & and |. Read the ValueError guide.(a > 2) & (a < 8); without brackets the operators run in a different order and the result is wrong or an error.
import numpy as np a = np.array([12, 45, 7, 60, 33]) mask = a > 20 print(mask) print(a[mask]) print(a[a % 2 == 0])
import numpy as np a = np.array([5, 15, 25, 35, 45]) print(a[(a > 10) & (a < 40)]) print(a[(a < 10) | (a > 40)]) print(a[~(a > 30)])
import numpy as np marks = np.array([35, 82, 47, 91, 28, 66]) passed = marks >= 40 print(passed.sum(), "passed") print(np.count_nonzero(marks > 80), "above 80") print(passed.mean())
import numpy as np marks = np.array([35, 82, 47, 28]) print(np.where(marks >= 40, "Pass", "Fail")) print(np.where(marks >= 40, marks, 0))
import numpy as np readings = np.array([4, -2, 7, -5, 3]) readings[readings < 0] = 0 print(readings)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import numpy as np a = np.array([5, 12, 8, 20]) print(a > 10)
A comparison gives a Boolean array, one True or False per element.
import numpy as np a = np.array([5, 12, 8, 20]) print(a[a > 10])
A Boolean mask keeps only the elements where it is True.
import numpy as np a = np.array([3, 8, 1, 9]) print((a > 2).sum())
True counts as 1, so summing a mask counts the matches.
Use & with brackets around each condition. and does not work element by element.
import numpy as np a = np.array([4, -2, 7, -5]) a[a < 0] = 0 print(a)
Assigning through a mask changes only the selected elements.