Data-cleaning rules often need to replace threshold breaches while leaving every other array element and the original ordering intact. NumPy applies that rule across the array with a boolean mask instead of a Python loop.
The np.where(condition, x, y) function builds a new array by choosing values from x at true positions and y elsewhere. The condition and branch values must broadcast to a common shape, so a scalar replacement works without constructing a full replacement array.
Boolean mask assignment changes the selected elements of its target array, while a separate working copy preserves the original values for later code. That distinction makes the mutation boundary explicit before either replacement method is chosen.
Related: Filter with a boolean mask
Related: Replace NaN and infinity
Related: Filter NaN values
Steps to replace NumPy array values conditionally:
- Create array-replace-conditional.py with the source array and its low-score mask.
- array-replace-conditional.py
import numpy as np scores = np.array([35, 72, 88, 41, 93]) low_score = scores < 50
- Append the np.where() replacement section below low_score.
- array-replace-conditional.py
adjusted = np.where(low_score, 50, scores) labels = np.where(scores >= 70, "pass", "review")
np.where() returns new arrays. Both scalar branches broadcast across the five positions in scores.
- Append the mask-assignment verification section below labels.
- array-replace-conditional.py
in_place = scores.copy() in_place[low_score] = 50 np.testing.assert_array_equal(adjusted, [50, 72, 88, 50, 93]) np.testing.assert_array_equal(in_place, adjusted) np.testing.assert_array_equal(scores, [35, 72, 88, 41, 93]) print("low score mask:", low_score) print("np.where adjusted:", adjusted) print("mask assignment adjusted:", in_place) print("labels:", labels) print("source array:", scores)
The assertions stop the script if either replacement changes the wrong position, the methods disagree, or mask assignment alters the source array.
- Run the completed conditional replacement script.
$ python3 array-replace-conditional.py low score mask: [ True False False True False] np.where adjusted: [50 72 88 50 93] mask assignment adjusted: [50 72 88 50 93] labels: ['review' 'pass' 'pass' 'review' 'pass'] source array: [35 72 88 41 93]
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.