【问题标题】:Swaping the negative values into zeroes in a numpy array Python在numpy数组Python中将负值交换为零
【发布时间】:2021-10-20 23:50:06
【问题描述】:

如何编写将a 的所有负值交换为零的代码。

import numpy as np 

a = np.array([12,12,123,4,-4,0.15,-100])

预期输出:

[12,12,123,4,0,0.15,0]

【问题讨论】:

    标签: python arrays numpy indexing format


    【解决方案1】:

    你可以使用numpy中的clip函数

    https://numpy.org/doc/stable/reference/generated/numpy.clip.html

    a.clip(min = 0)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      format_number = lambda n: n if n % 1 else int(n)
      a = list(map(lambda n: 0 if n < 0 else format_number(n), a))
      print(a)
      

      输出:

      [12, 12, 123, 4, 0, 0.15, 0]
      

      【讨论】: