Choosing Array Values with np.where
Introduction
Welcome to the final lesson of Filtering and Replacing with Masks and np.where. We’re on lesson 4 of 4. So far, we’ve used masks to select values, filter rows, and summarize matches. Now we’ll use a mask to choose a value for every cell in a new array. We’ll build temperature labels, clean sensor readings, calculate pay with two formulas, and assign grades with three outcomes.
The Shape of np.where
Think of np.where as making a choice cell by cell. It checks a condition, then puts the true-branch value or the false-branch value in that position of a new array. The condition, the true-branch value, and the false-branch value must be broadcast-compatible, and the result takes their common broadcast shape. In this lesson, each branch is either a single number or an array shaped like the source table, so every result keeps the source table’s shape. We’ll start by labeling temperatures: values of 20 or higher receive 1, and values below 20 receive 0.
The arguments are the condition, the value to use when it is true, and the value to use when it is false. Here, the condition is a 3-by-3 array and both branches are single numbers, so the labels form a 3-by-3 table:
The comparison includes values equal to 20, so both cells containing exactly 20 receive a 1. The result is a separate label array; temperatures remains unchanged.
Keeping Unchanged Cells with the Original Array
Sometimes we want to replace only the cells that match a condition and keep the rest. We can do that by using the original array as one branch. Here, negative sensor readings become 0, while every nonnegative reading is selected from readings itself.
The three negative readings are now 0, and every other value is copied over as it was:
The third argument, readings, tells NumPy what to put wherever the condition is false. This differs from using constants in both branches, as in the temperature labels: here, the result keeps the original values in those positions. The new cleaned array contains the replacements, and the source table stays untouched.
