Python Practice › NumPy Programs › Program 75

Replace negative values

EasyNumPy Programs · 75 of 100

Write a NumPy program to replace negative values with 1.

Advertisement
Input
[[4, 8, -5], [2, -9, 6]]
Output
[[4 8 1]
 [2 1 6]]

Approach

  1. Assign through a mask.

Solution

Python
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.

More numpy programs

← All 100 NumPy Programs

Leave a Comment