Back to Practice
#0076

Mask Values Above a Threshold

EasyNumPy12 min10 XP

Problem

Given a NumPy array and threshold, return a copy where values greater than threshold are replaced by threshold.

Why This Matters

Boolean masks are central to cleaning arrays, clipping outliers, and selecting rows for ML preprocessing.

Function Signature

def cap_values(values, threshold):

Examples

Example 1
Input[1, 10, 3], threshold = 5
Output[1, 5, 3]

Only 10 is above the threshold.

Constraints

  • Do not mutate the input array.
  • Preserve shape.
  • Return a NumPy array.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Cap one value
Inputnp.array([1,10,3]), 5
Expectednp.array([1,5,3])

Only values above threshold are replaced.

Hidden Test Categories
2D arrayno values above thresholdall values above threshold