Python | Replace negative value with zero in numpy array
Last Updated :
13 Mar, 2023
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_
3 min read
Replace NaN Values with Zeros in Pandas DataFrame NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to
5 min read
NumPy | Replace NaN values with average of columns Data visualization is one of the most important steps in machine learning and data analytics. Cleaning and arranging data is done by different algorithms. Sometimes in data sets, we get NaN (not a number) values that are unusable for data visualization. To solve this problem, one possible method is
5 min read
Python Pandas: Replace Zeros with Previous Non-Zero Value When working with a dataset, it's common to encounter zeros that need to be replaced with non-zero values. This situation arises in various contexts, such as financial data, sensor readings, or any dataset where a zero might indicate missing or temporary invalid data. Python's Pandas library provide
4 min read
Replace Negative Number by Zeros in Pandas DataFrame In this article, Let's discuss how to replace the negative numbers by zero in Pandas Approach: Import pandas module.Create a Dataframe.Check the DataFrame element is less than zero, if yes then assign zero in this element.Display the final DataFrame  First, let's create the dataframe. Python3 # imp
1 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
4 min read
Create a Numpy array filled with all zeros - Python In this article, we will learn how to create a Numpy array filled with all zeros, given the shape and type of array. We can use Numpy.zeros() method to do this task. Let's understand with the help of an example:Pythonimport numpy as np # Create a 1D array of zeros with 5 elements array_1d = np.zeros
2 min read
Slicing with Negative Numbers in Python Slicing is an essential concept in Python, it allows programmers to access parts of sequences such as strings, lists, and tuples. In this article, we will learn how to perform slicing with negative indexing in Python.Indexing in PythonIn the world of programming, indexing starts at 0, and Python als
5 min read
numpy.array_repr() in Python numpy.array_repr()function is used to convert an array to a string. Syntax : numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None) Parameters : arr : [array_like] Input array. max_line_width : [int, optional] The maximum number of columns the string should span. Newline cha
2 min read
Print a NumPy Array Without Scientific Notation in Python We have given you a Numpy array. We are going to display the Numpy array without scientific notation and with the given precision. In this article, we are going to explore different methods in Python. Example Input 1: Array = [123.456, 0.123456, 987.123] , Precision = 2Output 1: [123.46 0.12 987.12]
3 min read