Python – Replace negative values in an numpy array

numpypython

Is there a simple way of replacing all negative values in an array with 0?

I'm having a complete block on how to do it using a NumPy array.

E.g.

a = array([1, 2, 3, -4, 5])

I need to return

[1, 2, 3, 0, 5]

a < 0 gives:

[False, False, False, True, False]

This is where I'm stuck – how to use this array to modify the original array.

Best Solution

You are halfway there. Try:

In [4]: a[a < 0] = 0

In [5]: a
Out[5]: array([1, 2, 3, 0, 5])