Select Page

Python How to Replace Negative Value with Zero in Numpy Array

by | Programming, Python, Tips

This tutorial will go through three ways to replace negative values with zero in a numpy array.

The easiest way to do it is:

import numpy as np

arr = np.array([2, -3, 1, 10, -4, -2, 9])

print('Array: ', arr)

arr[ arr < 0 ] = 0

print('New array: ', arr)
Array:  [ 2 -3  1 10 -4 -2  9]
New array:  [ 2  0  1 10  0  0  9]

First Method: Naive Method

The first method uses the subscript operator to replace all negative values with 0.

# Import NumPy

import numpy as np

arr = np.array([2, -3, 1, 10, -4, -2, 9])

print('Array: ', arr)

arr[ arr < 0 ] = 0

print('New array: ', arr)

Let’s run the code to see the result:

Array:  [ 2 -3  1 10 -4 -2  9]
New array:  [ 2  0  1 10  0  0  9]

Second Method: numpy.where

The second method uses the numpy.where function to replace all negative elements in the array with a zero.

import numpy as np

arr = np.array([2, -3, 1, 10, -4, -2, 9])

print('Array: ', arr)

res = np.where(arr<0, 0, arr)

print('New array: ', res)

Let’s run the code to see the result:

Array:  [ 2 -3  1 10 -4 -2  9]
New array:  [ 2  0  1 10  0  0  9]

Third Method: numpy.clip

The third method uses the numpy.clip method to clip values outside of the interval [0, 999]. Values smaller than 0 become 0, and values larger than 999 become 999.

import numpy as np

arr = np.array([2, -3, 1, 10, -4, -2, 9])

max_val = 999

print('Array: ', arr)

res = np.clip(arr, 0, max_val)

print('New array: ', res)

Let’s run the code to see the result:

Array:  [ 2 -3  1 10 -4 -2  9]
New array:  [ 2  0  1 10  0  0  9]

Fourth Method: Compare array to array of zeros using numpy.maximum()

The fourth method compares the array with an array of zeros and takes the maximum element between the two using the numpy.maximum() function.

import numpy as np

arr = np.array([2, -3, 1, 10, -4, -2, 9])

zeros_arr = np.zeros(arr.shape, dtype=arr.dtype)

max_val = 999

print('Array: ', arr)

print('Array of zeros: ', zeros_arr)

res = np.maximum(arr, zeros_arr)

print('New array: ', res)

Let’s run the code to see the result:

Array:  [ 2 -3  1 10 -4 -2  9]
Array of zeros:  [0 0 0 0 0 0 0]
New array:  [ 2  0  1 10  0  0  9]

Summary

Congratulations on reading to the end of this tutorial!

For further reading on converting negative values to zeros, go to the following article:

Python How to Replace Negative Value with Zero in Pandas DataFrame

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!