Replace negative values in an numpy array

前端 未结 5 940
小蘑菇
小蘑菇 2020-12-04 20:47

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.



        
5条回答
  •  萌比男神i
    2020-12-04 21:02

    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 clip only 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 clip only the top half with clip(max=n). (This is much better than my previous suggestion, which involved passing NaN to the first parameter and using out to coerce the type.):

    >>> 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 aix's answer. I prefer clip for simple operations because it's self-documenting, but his answer is preferable for more complex operations.

提交回复
热议问题