How can I replace negative values with zeros in NumPy?

In NumPy, you can replace negative values with zeros by using the numpy.where() function. This function takes a condition as its first argument, and two arrays as its second and third arguments. The values from the second array are used when the condition evaluates to True, and the values from the third array are used when the condition evaluates to False. To replace all negative values, the condition should be set to numpy.less(arr, 0), where arr is the array containing the values to be modified. The second array should be set to 0, while the third array should be set to arr. This will replace all negative values in the given array with zeros.


You can use the following basic syntax to replace negative values with zero in NumPy:

my_array[my_array < 0] = 0

This syntax works with both 1D and 2D NumPy arrays.

The following examples show how to use this syntax in practice.

Example 1: Replace Negative Values with Zero in 1D NumPy Array

The following code shows how to replace all negative values with zero in a NumPy array:

import numpy as np

#create 1D NumPy array
my_array = np.array([4, -1, 6, -3, 10, 11, -14, 19, 0])

#replace negative values with zero in array
my_array[my_array < 0] = 0

#view updated array
print(my_array)

[ 4  0  6  0 10 11  0 19  0]

Notice that each negative value in the original array has been replaced with zero.

Example 2: Replace Negative Values with Zero in 2D NumPy Array

Suppose we have the following 2D NumPy array:

import numpy as np

#create 2D NumPy array
my_array = np.array([3, -5, 6, 7, -1, 0, -5, 9, 4, 3, -5, 1]).reshape(4,3)

#view 2D NumPy array
print(my_array)

[[ 3 -5  6]
 [ 7 -1  0]
 [-5  9  4]
 [ 3 -5  1]]

We can use the following code to replace all negative values with zero in the NumPy array:

#replace all negative values with zero in 2D array
my_array[my_array < 0] = 0

#view updated array
print(my_array)

[[3 0 6]
 [7 0 0]
 [0 9 4]
 [3 0 1]]

Notice that all negative values in the original 2D array have been replaced with zero.

The following tutorials explain how to perform other common tasks in NumPy:

x