How to use NumPy where() with multiple conditions and modify 2D array elements in Python

1 Answer

0 votes
import numpy as np
 
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
 
condition1 = arr % 2 == 0  # even numbers
condition2 = arr > 4      # numbers greater than 4
 
# Apply conditions and modify array elements
arr = np.where(condition1 & condition2, arr * 2, arr)
 
# If the element is even and greater than 4 → multiply it by 2
# Otherwise → leave it unchanged
 
print(arr)


  
'''
run:

[[ 1  2  3]
 [ 4  5 12]
 [ 7 16  9]]
  
'''

 



answered Feb 10 by avibootz
...