How to replace NumPy array values conditionally

Threshold cleanup and labeling tasks often need to change only the values that match a rule. In NumPy, that rule is usually a boolean mask, which keeps each replacement aligned with the array positions instead of moving the work into a Python loop.

Use np.where(condition, x, y) when the replacement should produce a new array. NumPy chooses values from the true branch where the mask is True and from the false branch everywhere else, and each branch can be a scalar or a broadcast-compatible array.

Use boolean mask assignment when an existing array or a deliberate copy should change in place. Copy the source first when later code still needs the original values, and keep compound conditions in a named mask so the threshold and replacement policy remain visible during review.

Steps to replace NumPy array values conditionally:

  1. Create a script that compares np.where() with mask assignment on a copy.
    array-replace-conditional.py
    import numpy as np
     
    scores = np.array([35, 72, 88, 41, 93])
     
    low_score = scores < 50
    adjusted = np.where(low_score, 50, scores)
    labels = np.where(scores >= 70, "pass", "review")
     
    in_place = scores.copy()
    in_place[low_score] = 50
     
    print("scores:", scores)
    print("low score mask:", low_score)
    print("np.where adjusted:", adjusted)
    print("mask assignment adjusted:", in_place)
    print("labels:", labels)
    print("changed positions:", np.flatnonzero(adjusted != scores))
    print("source unchanged:", np.array_equal(scores, np.array([35, 72, 88, 41, 93])))
    print("methods match:", np.array_equal(adjusted, in_place))

    np.where() returns adjusted as a new array. The mask assignment line writes into in_place because that variable is an explicit copy of scores.

  2. Run the script.
    $ python array-replace-conditional.py
    scores: [35 72 88 41 93]
    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']
    changed positions: [0 3]
    source unchanged: True
    methods match: True
  3. Verify that both replacement methods changed the same positions.

    changed positions: [0 3] identifies the scores below 50. methods match: True confirms np.where() and mask assignment produced the same adjusted values.

  4. Confirm that the source array remained unchanged.

    source unchanged: True means the original scores array still contains [35 72 88 41 93]. Use mask assignment only on an array that should be mutated.