Python Practice › NumPy Programs › Program 75
Replace negative values
Write a NumPy program to replace negative values with 1.
Input
[[4, 8, -5], [2, -9, 6]]
Output
[[4 8 1] [2 1 6]]
Approach
- Assign through a mask.
Solution
import numpy as npa = np.array([[4, 8, -5], [2, -9, 6]])a[a < 0] = 1print(a)Output
[[4 8 1] [2 1 6]]
Learn the concept
New to this topic? Read the lesson, then come back.