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.
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...
