The Wayback Machine - https://web.archive.org/web/20240622184501/https://www.geeksforgeeks.org/python-replace-negative-value-with-zero-in-numpy-array/
Open In App

Python | Replace negative value with zero in numpy array

Last Updated : 13 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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)


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




# 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)


Output:

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

  Method #3: Using np.clip 

Python3




# 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)


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




# 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)
  
# Creating a array of 0
zero_array = np.zeros(ini_array1.shape, dtype=ini_array1.dtype)
print("Zero array", zero_array)
 
# code to replace all negative value with 0
ini_array2 = np.maximum(ini_array1, zero_array)
 
# printing result
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
 
# Initialize the array
arr = np.array([1, 2, -3, 4, -5, -6])
 
# Print the initial array
print("Initial array:", arr)
 
# Replace negative values with zeros using a lambda function
replace_negatives = np.vectorize(lambda x: 0 if x < 0 else x)
result = replace_negatives(arr)
 
# Print the resulting array
print("Resulting array:", result)
#This code is contributed by Edula Vinay Kumar Reddy


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
 



Similar Reads

Replace NaN with zero and fill negative infinity values in Python
In this article, we will cover how to replace NaN with zero and fill negative infinity values in Python using NumPy. Example Input: [ nan -inf 5.] Output: [0.00000e+00 9.99999e+05 5.00000e+00] Explanation: Replacing NaN with 0 and negative inf with any value. numpy.nan_to_num method The numpy.nan_to_num method is used to replace Nan values with zer
3 min read
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values
In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex input values in Python. This method substitutes a nan value with a number and replaces positive infinity
4 min read
How to compute numerical negative value for all elements in a given NumPy array?
In this article, we will see how to compute the negative value for all elements in a given NumPy array. So, The negative value is actually the number which when added to any number becomes 0. Example: If we take a number as 4 then -4 is its negative number because when we add -4 to 4 we get sum as 0. Now let us take another example, Suppose we take
2 min read
Replace negative values with latest preceding positive value in Pandas DataFrame
In this article, we will discuss how to replace the negative value in Pandas DataFrame Column with the latest preceding positive value. While doing this there may arise two situations - Value remains unmodified if no proceeding positive value existsValue update to 0 if no proceeding positive value exists Let's discuss these cases in detail. Case 1:
3 min read
Python Program to Check Whether a Number is Positive or Negative or zero
Given a number. The task is to check whether the number is positive or negative or zero. Examples: Input: 5 Output: Positive Input: -5 Output: Negative Approach: We will use the if-elif statements in Python. We will check whether the number is greater than zero or smaller than zero or equal to zero. Below is the implementation. C/C++ Code # Python
2 min read
Test whether the elements of a given NumPy array is zero or not in Python
In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy.all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value. Syntax: numpy.all( array ) Parameters: An array Return: Boolean va
2 min read
NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
Program to check if a number is Positive, Negative, Odd, Even, Zero
Given a number n, the task is to check whether the given number is positive, negative, odd, even, or zero. Method 1 : A number is positive if it is greater than zero. We check this in the expression of if.If it is False, the number will either be zero or negative.This is also tested in subsequent expressions.In the case of odd and even A number is
15 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Practice Tags :
three90RightbarBannerImg