Python / Data Science Essentials Interview Questions
How does NumPy boolean masking and fancy indexing work?
Beyond basic integer indexing, NumPy supports two advanced selection mechanisms that are essential for data-cleaning and filtering tasks.
Boolean masking: A comparison on an array produces a boolean array of the same shape. Passing that boolean array back as an index selects only the True positions.
import numpy as np scores = np.array([88, 45, 72, 91, 60, 33, 95]) # Boolean mask mask = scores >= 70 print(mask) # [True False True True False False True] passing = scores[mask] print(passing) # [88 72 91 95] # Compound conditions mid_range = scores[(scores >= 60) & (scores < 90)] print(mid_range) # [88 72 60] â use & | ~ not and/or # Assign through a mask scores[scores < 50] = 50 # clamp low scores to 50 print(scores) # [88 50 72 91 60 50 95] # np.where â vectorised if/else grades = np.where(scores >= 70, 'Pass', 'Fail') print(grades) # ['Pass' 'Fail' 'Pass' 'Pass' 'Fail' 'Fail' 'Pass']
Fancy indexing: Pass an integer array (or list) as an index to select arbitrary elements in any order. Unlike slicing, fancy indexing always returns a copy, not a view.
data = np.array([10, 20, 30, 40, 50]) idx = np.array([4, 1, 4, 0]) # can repeat indices print(data[idx]) # [50 20 50 10] # 2-D fancy indexing m = np.arange(16).reshape(4, 4) rows = [0, 2]; cols = [1, 3] print(m[rows, cols]) # m[0,1] and m[2,3]: [1 11]
More Related questions...