In this python numpy program, we will replace the negative values in an NumPy array.
Steps to solve the program
- Import the numpy library as np.
- Create an array using np.array().
- Replace the negative values in the given array with 1 using indexing and logic.
- Print the output.
import numpy as np
x = np.array([[4,8,-5],[2,-9,6]])
print("Old: \n",x)
x[x<0] = 1
print("New: \n",x)
Output :
Old:
[[ 4 8 -5]
[ 2 -9 6]]
New:
[[4 8 1]
[2 1 6]]