4

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

sacuL
  • 49,704
  • 8
  • 81
  • 106
Achintha Ihalage
  • 2,310
  • 4
  • 20
  • 33
  • Related: [Difference between 'and' (boolean) vs. '&' (bitwise) in python](https://stackoverflow.com/questions/22646463/difference-between-and-boolean-vs-bitwise-in-python-why-difference-i) – jpp Oct 22 '18 at 16:41

2 Answers2

7

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.  ])   
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Could you please explain me how this operation happens, and why it is faster than replacing with a for loop? – Achintha Ihalage Oct 22 '18 at 16:51
  • 1
    `(arr>1.0)` and `(arr<1.5)` finds the indices for which the conditions are True and `&` combines them. The result is the indices at which the values fulfill these conditions. Those indices inside `[ ]` acts as the input indices for `arr[ ]` and gives you the elements for which the condition holds. The assignment operator `=` then assigns 1.0 to the values on those indices. – Sheldore Oct 22 '18 at 18:42
2

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.

Stephen C
  • 1,966
  • 1
  • 16
  • 30