Replace each element that fails a condition with a fixed value. A loop uses a ternary expression to keep each value if it is non-negative, substituting 0 otherwise. The replay shows result accumulating one element per iteration, with negative values silently replaced.

By hand

With NumPy

np.where(a >= 0, a, 0) applies the same logic elementwise: where the condition is True it takes the corresponding element of a, where False it uses 0. No explicit loop is needed.

naive.py
values = [3, -1, 5, -2, 0, 4]
result = []
for v in values:
    result.append(v if v >= 0 else 0)
print('RESULT:', result)
library.py
import numpy as np

values = [3, -1, 5, -2, 0, 4]
a = np.array(values)
result = np.where(a >= 0, a, 0)
print('shape:', result.shape)
print('dtype:', result.dtype)
print('values:', result.tolist())
print('RESULT:', result.tolist())
shape: (6,)
dtype: int64
values: [3, 0, 5, 0, 0, 4]
RESULT: [3, 0, 5, 0, 0, 4]

Implementation notes

  • np.where(cond, x, y) is the vectorized ternary. x and y can be scalars or arrays of the same shape as cond — all three are broadcast together.
  • This pattern is commonly used for clamping: replace values below a floor (np.where(a < lo, lo, a)) or above a ceiling, or to zero out negatives before a log transform.
  • np.where always evaluates both x and y before selecting — there is no short-circuit. Side effects in x or y run regardless of the condition.
  • For the equivalent pure-Python pattern see map-transform in the python-data-basics book.
  • Shape, dtype, and values are shown explicitly here because ndarray.__repr__ output varies with NumPy version and print options.