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]
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
