Python / Data Science Essentials Interview Questions
What is np.where and how is it used for conditional array creation?
np.where is NumPy's vectorised if/else for arrays. In its three-argument form it returns a new array built element-by-element: where the condition is True, use values from x; where False, use values from y. It is the correct alternative to writing a Python loop with an if-statement inside.
import numpy as np scores = np.array([88, 45, 72, 91, 60, 33, 95]) # Classify into Pass / Fail without a loop labels = np.where(scores >= 70, 'Pass', 'Fail') # ['Pass' 'Fail' 'Pass' 'Pass' 'Fail' 'Fail' 'Pass'] # Apply a discount: over 80 gets 20% off, rest gets 5% off prices = np.array([100.0, 200.0, 50.0, 150.0]) discounted = np.where(prices > 80, prices * 0.80, prices * 0.95) # [95. 160. 47.5 120.] # Chain multiple conditions using np.select conditions = [ scores >= 90, (scores >= 70) & (scores < 90), scores < 70, ] choices = ['A', 'B', 'C'] grades = np.select(conditions, choices, default='F') # ['B' 'C' 'B' 'A' 'C' 'C' 'A'] # One-argument form: returns indices where condition is True failing_indices = np.where(scores < 70) # (array([1, 4, 5]),) â tuple of index arrays failing_scores = scores[failing_indices] # [45 60 33]
np.select generalises np.where to multiple conditions — the first matching condition wins. Use it whenever you have more than two output categories; chaining nested np.where calls quickly becomes unreadable.
More Related questions...