w3resource logo
Python Exercises

Python NumPy: Remove the negative values in a numpy array with 0

Python NumPy: Array Object Exercise-90 with Solution

Write a Python program to remove the negative values in a numpy array with 0.

Sample Solution:-

Python Code:

import numpy as np
x = np.array([-1, -4, 0, 2, 3, 4, 5, -6])
print("Original array:")
print(x)
print("Replace the negative values of the said array with 0:")
x[x < 0] = 0
print(x)

Sample Output:

Original array:                                                        
[-1 -4  0  2  3  4  5 -6]                                              
Replace the negative values of the said array with 0:                  
[0 0 0 2 3 4 5 0]

Python Code Editor:

import numpy as np
x = np.array([-1, -4, 0, 2, 3, 4, 5, -6])
print("Original array:")
print(x)
print("Replace the negative values of the said array with 0:")
x[x < 0] = 0
print(x)

Improve this sample solution and post your code through Disqus