Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
Python | Replace negative value with zero in numpy array
Next article icon

Python | Replace negative value with zero in numpy array

Last Updated : 13 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
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
 


Next Article
Python | Replace negative value with zero in numpy array

G

garg_ak0109
Improve
Article Tags :
  • Python
  • Python-numpy
  • Python numpy-program
Practice Tags :
  • python

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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences