w3resource

NumPy: Replace the negative values in a NumPy array with 0


Replace Negative Values with 0

Write a NumPy program to replace the negative values in a NumPy array with 0.

Pictorial Presentation:

Python NumPy: Replace the negative values in a NumPy array with 0

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' containing integers
x = np.array([-1, -4, 0, 2, 3, 4, 5, -6])

# Printing a message indicating the original array will be displayed
print("Original array:")

# Printing the original array 'x' with its elements
print(x)

# Printing a message indicating the replacement of negative values in the array with 0
print("Replace the negative values of the said array with 0:")

# Replacing all negative values in the array 'x' with 0 using boolean indexing
x[x < 0] = 0

# Printing the modified array 'x' after replacing negative values with 0
print(x)

Sample Output:

Original array:                                                        
[-1 -4  0  2  3  4  5 -6]                                              
Replace the negative values of the said array with 0:                  
[0 0 0 2 3 4 5 0]

Explanation:

In the above code –

x = np.array(...) – This part creates a NumPy array 'x' with the given elements.

x[x < 0] = 0: Use boolean indexing to identify and replace all negative elements in the array 'x' with zeros. The expression x < 0 creates a boolean array with the same shape as 'x', where each element is True if the corresponding element in 'x' is negative and False otherwise. The assignment x[x < 0] = 0 replaces all elements of 'x' for which the corresponding boolean value is True with zeros.

print(x): Print the modified array 'x'.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to replace negative values in an array with 0 using boolean indexing.
  • Create a function that scans an array for negative values and updates them to 0 without using loops.
  • Test the replacement by verifying that the sum of negative values becomes 0 after the operation.
  • Compare the use of np.where and direct indexing approaches to replace negative values and analyze performance.

Go to:


PREV : Remove Specific Elements in Array
NEXT : Remove Rows with Non-Numeric Values


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.