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
# Python code to demonstrate# to replace negative value with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # code to replace all negative value with 0ini_array1[ini_array1<0] = 0 # printing resultprint("New resulting array: ", ini_array1) |
Output:
initial array [ 1 2 -3 4 -5 -6] New resulting array: [1 2 0 4 0 0]
Method #2: Using np.where
# Python code to demonstrate# to replace negative values with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # code to replace all negative value with 0result = np.where(ini_array1<0, 0, ini_array1) # printing resultprint("New resulting array: ", result) |
Output:
initial array [ 1 2 -3 4 -5 -6] New resulting array: [1 2 0 4 0 0]
Method #3: Using np.clip
# Python code to demonstrate# to replace negative values with 0import numpy as np # supposing maxx value array can holdmaxx = 1000 ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # code to replace all negative value with 0result = np.clip(ini_array1, 0, 1000) # printing resultprint("New resulting array: ", result) |
Output:
initial array [ 1 2 -3 4 -5 -6] New resulting array: [1 2 0 4 0 0]
Method #4: Comparing the given array with an array of zeros and write in the maximum value from the two arrays as the output.
# Python code to demonstrate# to replace negative values with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # Creating a array of 0zero_array = np.zeros(ini_array1.shape, dtype=ini_array1.dtype)print("Zero array", zero_array) # code to replace all negative value with 0ini_array2 = np.maximum(ini_array1, zero_array) # printing resultprint("New resulting array: ", ini_array2) |
Output:
initial array [ 1 2 -3 4 -5 -6] Zero array [0 0 0 0 0 0] New resulting array: [1 2 0 4 0 0]


