Numpy replace negative values ​​in an array

Can anyone advise a simple way to replace all negative values ​​in an array with 0?

I have a complete block how to do this using a numpy array

eg.

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 am stuck - how to use this array to modify the original array

+57
python numpy
Apr 26 2018-12-12T00:
source share
5 answers

You're halfway there. Try:

 In [4]: a[a < 0] = 0 In [5]: a Out[5]: array([1, 2, 3, 0, 5]) 
+91
Apr 26 2018-12-12T00:
source share

Try numpy.clip :

 >>> import numpy >>> a = numpy.arange(-10, 10) >>> a array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a.clip(0, 10) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

You can only click the bottom half with clip(0) .

 >>> a = numpy.array([1, 2, 3, -4, 5]) >>> a.clip(0) array([1, 2, 3, 0, 5]) 

You can only pin the top half with clip(max=n) . (This is much better than my previous sentence, which included passing NaN into the first parameter and using out to force type input.):

 >>> a.clip(max=2) array([ 1, 2, 2, -4, 2]) 

Another interesting approach is to use where :

 >>> numpy.where(a <= 2, a, 2) array([ 1, 2, 2, -4, 2]) 

Finally, consider the aix answer. I prefer clip for simple operations because it is self-documenting, but its answer is preferable for more complex operations.

+65
Apr 26 '12 at 14:05
source share

Another minimal Python solution without using numpy:

 [0 if i < 0 else i for i in a] 

No need to define any additional features.

 a = [1, 2, 3, -4, -5.23, 6] [0 if i < 0 else i for i in a] 

gives:

 [1, 2, 3, 0, 0, 6] 
+8
Apr 26 2018-12-12T00:
source share

And one more possibility:

 In [2]: a = array([1, 2, 3, -4, 5]) In [3]: where(a<0, 0, a) Out[3]: array([1, 2, 3, 0, 5]) 
+3
Jul 10 '15 at 14:20
source share

Here is a way to do it in Python without numpy. Create a function that returns what you want and use a list or map comprehension.

 >>> a = [1, 2, 3, -4, 5] >>> def zero_if_negative(x): ... if x < 0: ... return 0 ... return x ... >>> [zero_if_negative(x) for x in a] [1, 2, 3, 0, 5] >>> map(zero_if_negative, a) [1, 2, 3, 0, 5] 
+2
Apr 26 2018-12-12T00:
source share



All Articles