Python | Replace negative value with zero in numpy array

Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem.

Method #1: Naive Method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# to replace negative value with 0
import numpy as np
  
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
  
# printing initial arrays
print("initial array", ini_array1)
  
# code to replace all negative value with 0
ini_array1[ini_array1<0] = 0
  
# printing result
print("New resulting array: ", ini_array1)

chevron_right


Output:

initial array [ 1  2 -3  4 -5 -6]
New resulting array:  [1 2 0 4 0 0]

 
Method #2: Using np.where

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# to replace negative values with 0
import numpy as np
  
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
  
# printing initial arrays
print("initial array", ini_array1)
  
# code to replace all negative value with 0
result = np.where(ini_array1<0, 0, ini_array1)
  
# printing result
print("New resulting array: ", result)

chevron_right


Output:

initial array [ 1  2 -3  4 -5 -6]
New resulting array:  [1 2 0 4 0 0]

 
Method #3: Using clip

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# to replace negative values with 0
import numpy as np
  
# supposing maxx value array can hold
maxx = 1000
  
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
  
# printing initial arrays
print("initial array", ini_array1)
  
# code to replace all negative value with 0
result = np.clip(ini_array1, 0, 1000)
  
# printing result
print("New resulting array: ", result)

chevron_right


Output:

initial array [ 1  2 -3  4 -5 -6]
New resulting array:  [1 2 0 4 0 0]


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.