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
Python3
import numpy as np
ini_array1 = np.array([ 1 , 2 , - 3 , 4 , - 5 , - 6 ])
print ("initial array", ini_array1)
ini_array1[ini_array1< 0 ] = 0
print ("New resulting array: ", ini_array1)
|
Output:
initial array [ 1 2 -3 4 -5 -6]
New resulting array: [1 2 0 4 0 0]
The time complexity of this code is O(n), where n is the size of the ini_array1.
The auxiliary space complexity of this code is O(1), which means it uses a constant amount of extra space, regardless of the input size.
Method #2: Using np.where
Python3
import numpy as np
ini_array1 = np.array([ 1 , 2 , - 3 , 4 , - 5 , - 6 ])
print ("initial array", ini_array1)
result = np.where(ini_array1< 0 , 0 , ini_array1)
print ("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
Python3
import numpy as np
maxx = 1000
ini_array1 = np.array([ 1 , 2 , - 3 , 4 , - 5 , - 6 ])
print ("initial array", ini_array1)
result = np.clip(ini_array1, 0 , 1000 )
print ("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.
Python3
import numpy as np
ini_array1 = np.array([ 1 , 2 , - 3 , 4 , - 5 , - 6 ])
print ("initial array", ini_array1)
zero_array = np.zeros(ini_array1.shape, dtype = ini_array1.dtype)
print ("Zero array", zero_array)
ini_array2 = np.maximum(ini_array1, zero_array)
print ("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]
The time complexity of the given Python code is O(n), where n is the size of the input array ini_array1
The auxiliary space complexity of the code is O(n), as it creates a new array of the same size as the input array to store the 0 values.
Method #5: Using np.vectorize
You could use a lambda function to transform the elements of the array and replace negative values with zeros. This can be done using the NumPy vectorize function.
Python3
import numpy as np
arr = np.array([ 1 , 2 , - 3 , 4 , - 5 , - 6 ])
print ( "Initial array:" , arr)
replace_negatives = np.vectorize( lambda x: 0 if x < 0 else x)
result = replace_negatives(arr)
print ( "Resulting array:" , result)
|
Output:
Initial array: [ 1 2 -3 4 -5 -6]
Resulting array: [1 2 0 4 0 0]
Time complexity: O(n) where n is the number of elements in the array
Auxiliary Space: O(n) as a new array with the transformed elements is created
Last Updated :
13 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...