Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace value in array when greater than x [duplicate]

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.

like image 376
Essex Avatar asked Mar 13 '23 12:03

Essex


2 Answers

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. ])
like image 133
Colonel Beauvel Avatar answered Mar 16 '23 03:03

Colonel Beauvel


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

like image 32
Matroskin Avatar answered Mar 16 '23 04:03

Matroskin