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.
Additional Resources
The following tutorials explain how to perform other common tasks in NumPy:
How to Fill NumPy Array with Values
How to Remove Specific Elements from NumPy Array
How to Replace Elements in NumPy Array
How to Get Specific Row from NumPy Array