Replace numpy ndarry negative elements with 0 (zero)

Viewed 300

suppose I have a numpy ndarray

[[2, -7, 5], [-6, 2, 0] [1, -4, 2], [-2, 6, 8]]

How to get a numpy nd arry with all negative elements replaced by 0:

[[2, 0, 5], [0, 2, 0] [1, 0, 2], [0, 6, 8]]

Thank you for your valuable time.

2 Answers

You can use np.clip for this, clipping between zero and infinity:

arr = np.array([[2, -7, 5], [-6, 2, 0], [1, -4, 2], [-2, 6, 8]])

np.clip(arr, a_min = 0, a_max = np.inf)

array([[2., 0., 5.],
       [0., 2., 0.],
       [1., 0., 2.],
       [0., 6., 8.]])

Otherwise, you can use something like this (note this changes the array in place):

arr[arr <= 0] = 0

>>> arr
array([[2, 0, 5],
       [0, 2, 0],
       [1, 0, 2],
       [0, 6, 8]])

You could use np.where() too:

arr = np.array([[2, -7, 5], [-6, 2, 0], [1, -4, 2], [-2, 6, 8]])
result = np.where(arr<0, 0, arr)

Output:

[[2 0 5]

 [0 2 0]
 [1 0 2]
 [0 6 8]]
Related