0
0
NumPydata~10 mins

np.where() for conditional selection in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - np.where() for conditional selection
Start with array
Apply condition
np.where(condition, x, y)
For each element: if condition True -> take x else y
Return new array with selected values
np.where() checks a condition on each element and picks values from two options accordingly, creating a new array.
Execution Sample
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
result = np.where(arr > 3, arr, 0)
print(result)
This code replaces elements in arr with 0 if they are not greater than 3.
Execution Table
StepElement IndexElement ValueCondition (arr > 3)Value if TrueValue if FalseResult Element
101False100
212False200
323False300
434True404
545True505
6-----[0 0 0 4 5]
💡 All elements processed, result array created with condition applied.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5Final
arr[1 2 3 4 5][1 2 3 4 5][1 2 3 4 5][1 2 3 4 5][1 2 3 4 5][1 2 3 4 5][1 2 3 4 5]
result[][0][0 0][0 0 0][0 0 0 4][0 0 0 4 5][0 0 0 4 5]
Key Moments - 2 Insights
Why does np.where return 0 for elements not greater than 3 instead of the original element?
Because np.where uses the second argument (here 0) for elements where the condition is False, as shown in execution_table rows 1-3.
Is the original array changed after np.where is applied?
No, np.where creates a new array with selected values; the original array 'arr' remains unchanged as shown in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result element at index 2?
A3
B0
C2
D4
💡 Hint
Check row 3 in the execution_table where index 2 is processed.
At which step does the condition become True for the first time?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Condition (arr > 3)' column in execution_table rows.
If we change the false value from 0 to -1, how would the result element at index 1 change?
AIt would be 2
BIt would be -1
CIt would be 0
DIt would be 1
💡 Hint
Refer to how np.where picks values based on condition in execution_table.
Concept Snapshot
np.where(condition, x, y)
Checks each element against condition.
If True, picks x; if False, picks y.
Returns new array with selected values.
Does not change original array.
Full Transcript
This visual execution shows how np.where() works for conditional selection. We start with an array and a condition (arr > 3). For each element, np.where checks if the condition is true. If yes, it picks the element itself; if no, it picks 0. The execution table traces each element's check and the resulting value. The variable tracker shows the result array building up step by step, while the original array stays the same. Key moments clarify why values change and that the original array is not modified. The quiz tests understanding of element-wise selection and condition evaluation.