2016-04-25 28 views
2

我遇到了一个有点简单的问题。我有一组数据,我想替换每个值,如果该值大于X.当大于x时,替换数组中的值

为了解决这个问题,我写了一个小脚本例子给出了同样的想法更大:

import numpy as np 

# Array creation 

array = np.array([0.5, 0.6, 0.9825]) 

print array 

# If value > 0.7 replace by 0. 

new_array = array[array > 0.7] == 0 

print new_array 

我想获得:

>>> [0.5, 0.6, 0] # 0.9825 is replaced by 0 because > 0.7 

谢谢你,如果你我能帮助;)

编辑:

我没有找到这个主题可以帮助我:Replace all elements of Python NumPy Array that are greater than some value 由@ColonelBeauvel给出的答案没有在上一篇文章中注意到。

回答

3

我不知道为什么在链接不提供这个解决方案提供@DonkeyKong:

np.where(arr>0.7, 0, arr) 
#Out[282]: array([ 0.5, 0.6, 0. ]) 
+0

非常感谢!它工作得很好!我也在观看'np.where';) – Deadpool

0

怎么样

a = [0.5, 0.6, 0.9825] 
b = [(lambda i: 0 if i > 0.7 else i)(i) for i in a] 

这里是lambda expression里面list comprehensions。 检查链接

+1

尽管这段代码可能会回答这个问题,但提供关于为什么和/或如何回答问题的额外内容会显着提高其长期价值。请[编辑]你的答案,添加一些解释。 – CodeMouse92