4

I get a little problem with a simple idea. I have an array of data and I would like to replace each value if the value is greater than X.

To solve that, I wrote a little script as example which give the same idea :

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

I would like to obtain :

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

Thank you if you could me help ;)

EDIT :

I didn't find How this subject could help me : Replace all elements of Python NumPy Array that are greater than some value The answer given by @ColonelBeauvel is not noticed in the previous post.

Community
  • 1
  • 1
Essex
  • 6,042
  • 11
  • 67
  • 139

2 Answers2

6

I wonder why this solution is not provided in the link @DonkeyKong provided:

np.where(arr>0.7, 0, arr)
#Out[282]: array([ 0.5,  0.6,  0. ])
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
1

how about

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

?

here is lambda expression inside list comprehensions. check the links

Matroskin
  • 429
  • 4
  • 5
  • 2
    While this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – CodeMouse92 Apr 25 '16 at 20:29