Replace the negative values in an NumPy array

In this python numpy program, we will replace the negative values in an NumPy array.

Steps to solve the program
  1. Import the numpy library as np.
  2. Create an array using np.array().
  3. Replace the negative values in the given array with 1 using indexing and logic.
  4. 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]]
				
			

add an extra column to an array.

remove all rows in a NumPy array that contain non-numeric values.

Leave a Comment