Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing numpy array elements within a given range then and there

Say I have following numpy array.

arr = np.array( [ 1.0, 1.1, 1.44, 1.8, 1.0, 1.67, 1.23, 1.0] )

I could replace all elements that are equal to 1.0 with 0.0, simply using following line.

arr[arr==1.0] = 0.0

How could I replace all elements between, say 1.0 - 1.5 with 1.0 without running through a for loop.

Basically what I ask is how to do the following

arr[arr>1.0 and arr<1.5] = 1.0

Thanks

like image 945
Achintha Ihalage Avatar asked Jan 28 '23 06:01

Achintha Ihalage


2 Answers

You just need to club the conditions together using & and enclosing the conditions in ( )

arr[(arr>1.0) & (arr<1.5)] = 1.0

# array([1.  , 1.  , 1.  , 1.8 , 1.  , 1.67, 1.  , 1.  ])   
like image 102
Sheldore Avatar answered Jan 31 '23 09:01

Sheldore


You can do it like this

arr = np.array( [ 1.0, 1.1, 1.44, 1.8, 1.0, 1.67, 1.23, 1.0] )
arr[(1<arr) & (arr<1.5)] = 1.0

You need to use the bit-wise & to join the arrays into one array mask.

like image 31
Stephen C Avatar answered Jan 31 '23 09:01

Stephen C