Conditional Selectors: np.where(), np.select() & np.extract()
Conditional Selection with np.where() & np.select()
Conditional logic is the backbone of data engineering and scientific pipelines. Often, you need to assign values depending on whether conditions are met—similar to Excel's IF() function or SQL's CASE WHEN ... THEN ... ELSE statements.
NumPy provides two workhorses for conditional operations:
- 1
np.where(): Vectorized ternary operatorif-elseand index extraction. - 2
np.select(): Scalable multi-condition decision tables for complex business logic.
1. Vectorized If-Else with np.where(condition, x, y)
The ternary syntax of np.where takes three arguments: np.where(condition, value_if_true, value_if_false)
Both value_if_true and value_if_false can be scalar constants or entire arrays of matching shape:
Output:
2. Using np.where(condition) to Extract Indices
When called with only one argument (the condition), np.where() acts as an index finder, returning a tuple of coordinate arrays where the condition evaluates to True:
Output:
In 2D Matrices:
In a 2D array, np.where() returns a tuple of (row_indices, col_indices):
3. Multi-Condition Logic with np.select()
When your logic involves more than two outcomes (e.g. grading scale A, B, C, D, F), nesting np.where() calls quickly turns into unreadable spaghetti code:
Instead, use np.select(condlist, choicelist, default=default_value):
Output:
Real-World Business Example: Progressive Tax Rates
Multiple Choice Questions
1. What does np.where(arr > 5, 1, 0) return?
A. A tuple of row and column indices where elements exceed 5 B. A new array where elements > 5 become 1 and all other elements become 0 C. A boolean mask D. The count of elements greater than 5 Answer: B Explanation: When passed three arguments (condition, x, y), np.where performs element-wise conditional selection, picking x when True and y when False.
2. What is returned when np.where(condition) is called with only ONE argument?
A. A boolean array B. A tuple of index arrays indicating where the condition is True C. The sum of all elements matching the condition D. An error requiring 3 parameters Answer: B Explanation: Calling np.where with only a condition is equivalent to np.nonzero(condition), returning a tuple of integer index arrays along each axis for all True positions.
3. Why is np.select() preferred over nested np.where() calls for 3 or more branches?
A. np.select is written in Fortran while np.where is written in Python B. np.select avoids deeply nested syntactical complexity and evaluates conditions sequentially with clear paired lists C. np.select supports string inputs whereas np.where only supports floats D. np.where cannot be chained more than twice Answer: B Explanation: np.select(condlist, choicelist, default) mirrors SQL CASE WHEN logic, keeping code linear, readable, and maintainable when handling complex decision branches.
4. Given arr = np.array([10, 20, 30]), what is the output of np.where(arr > 15)[0]?
A. array([1, 2]) B. array([20, 30]) C. array([True, True]) D. 2 Answer: A Explanation: Elements at index 1 (20) and index 2 (30) exceed 15. np.where(arr > 15) returns (array([1, 2]),), so accessing [0] yields the 1D index array [1, 2].
5. In np.select(conditions, choices, default=0), what happens if an element satisfies multiple conditions simultaneously?
A. A ValueError is thrown B. The first condition in the list that evaluates to True determines the selected choice C. All matching choices are added together D. The default value is selected Answer: B Explanation: np.select checks conditions in the specified list order. The first matching condition encountered selects the corresponding choice, short-circuiting subsequent conditions for that element.
Reshaping Arrays (reshape with -1 auto-dimension)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Fancy Indexing with Integer Arrays | Reshaping Arrays (reshape with -1 auto-dimension) |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.