Replace negative values in an numpy array

前端 未结 5 942
小蘑菇
小蘑菇 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条回答
  •  天命终不由人
    2020-12-04 21:14

    Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.

    >>> 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]
    

提交回复
热议问题