Replace Values with Mask Practice Problem
This data science coding problem helps you practice Indexing, Slicing & Filtering, replace values with mask, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Indexing, Slicing & Filtering.
- Problem ID: 53
- Problem key: 53-replace-values-with-mask
- URL: https://datacrack.app/solve/53-replace-values-with-mask
- Difficulty: medium
- Topic: Indexing, Slicing & Filtering
- Module: NumPy Foundations
Problem Statement
# 🧩 Replace Values with Mask
---
### 🎯 Goal
In-place replacement using a boolean mask is one of the most common data cleaning operations: capping outliers, replacing negatives with zero (ReLU!), zeroing out certain features. This problem teaches **masked assignment** — modifying only the elements that satisfy a condition.
---
### 🔍 Masked Assignment
```python
arr = np.array([1, -2, 3, -4, 5])
arr[arr < 0] = 0 # Replace negatives with 0
# → [1, 0, 3, 0, 5]
```
Note: this **modifies the array in place**.
---
### 💻 Task
Implement `replace_values(data, condition, replacement)`.
---
### 📥 Input
- `data`: list of numbers
- `condition`: string — `"negative"`, `"above_100"`, or `"even"`
- `replacement`: number — the value to substitute
### 📤 Output
- A new list with the condition-matching values replaced
---
### 🧩 Starter Code
```python
import numpy as np
def replace_values(data, condition, replacement):
"""
Replace values matching a condition with a replacement value.
Args:
data (list): Input numbers
condition (str): "negative" | "above_100" | "even"
replacement (number): Value to replace with
Returns:
list: Modified array
"""
# TODO:
return arr.tolist()
```
---
### 💡 Example
```python
replace_values([1, -2, 3, -4, 5, -6], "negative", 0)
# Expected: [1, 0, 3, 0, 5, 0]
```
---
### 🔑 Key Concepts
- `arr[condition_mask] = value` — in-place assignment to selected elements
- Make a copy first if you don't want to modify the original: `arr = arr.copy()`
- `"negative"` condition = ReLU activation: `max(0, x)` applied element-wiseStarter Code
import numpy as np
def replace_values(data, condition, replacement):
"""
Replace values matching a condition with a replacement value.
Args:
data (list): Input numbers
condition (str): "negative" | "above_100" | "even"
replacement (number): Value to replace with
Returns:
list: Modified array
"""
# TODO:
return arr.tolist()