Python | Replace negative value with zero in numpy array

Method # 1: The Naive Method

# Python code for demonstration
# 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 values ​​with 0

ini_array1 [ini_array1 & lt; 0 ] = 0

 
# print result

print ( "New resulting array:" , ini_array1)

Exit:

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

Method # 2: Using np.where

# Python code for demo
# replace negative values ​​with 0

import numpy as np

 

ini_array1 = np.array ([ 1 , 2 , - 3 , 4 , - 5 , - 6 ])

 
# print initial macs sivov

print ( "initial array" , ini_array1)

 
# code to replace all negative values ​​with 0

result = np.where (ini_array1 & lt; 0 , 0 , ini_array1)

 
# print result

print ( " New resulting array: " , result)

Exit :

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

Method # 3: Using np.clip < / p>

# Python code for demonstration
# replace negative values ​​with 0

import numpy as np

 
# suppose the array of maxx values ​​can contain

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 values ​​with 0

result = np.clip (ini_array1, 0 , 1000 )

 
# print result

print ( "New resulting a rray: " , result)

Output:

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

Method # 4: Compare a given array with an array of zeros and write the maximum value of the two arrays as output.

# Python code for demonstration
# replace negative values ​​with 0

import numpy as np

  

ini_array1 = np.array ([ 1 , 2 , - 3 , 4 , - 5 , - 6 ])

 
# print initial arrays

print ( "initial array" , ini_array1)

 
# Create array 0

zero_array = np.zeros (ini_array1.shape, dtype = ini_array1.dtype)

print ( "Zero array" , zero_array)

  
# code to replace all negative values ​​with 0

ini_array2 = np.maximum (ini_array1, zero_array)

  
# print result

print ( "New resulting array:" , ini_array2)

Exit:

 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]