Data Science · Level 1 Filtering

Conditional Values with NumPy

Replace or label every value in one step with np.where(), the vectorized if/else behind data flags and categories.

  • np.where(condition, if_true, if_false)
  • Works on the whole array
  • Returns a new array

np.where(condition, a, b) picks a where the condition is true and b elsewhere, for every element at once. Trap: it returns a new array; assign the result, or nothing changes.

stock = np.array([0, 4, 0, 12])
np.where(stock == 0, "sold out", "in stock")
# array(['sold out', 'in stock', 'sold out', 'in stock'])

Write cap_scores(scores) that returns a new array where every score above 100 becomes 100, for example cap_scores(np.array([90, 130])) gives array([90, 100]).

solution.py
Test Suites Pending
Output