Articles → Numpy → Conditionally Selecting The Elements In An Array In Numpy
Conditionally Selecting The Elements In An Array In Numpy
Example
import numpy as np
arr = np.arange(1,10)
# Check the array for numbers greater than 5
result = arr > 5
print(arr[result])
- An array is created using the arange function with values from 1 to 9
- Check the value of the array greater than 5 using a single expression arr > 5 and put the result of the expression in an array ‘result’
- The result will be a boolean array with true and false values
Click to Enlarge
- The value from position 0 to 4 is false because the value at these positions is less than 5. The value from 5 to 8 is true because the value at these positions is greater than 5.
- Finally, print the value of arr[result], which returns the value from position 5 to 8 (all true values).
Click to Enlarge
import numpy as np
arr = np.arange(1,10)
print(arr[arr> 5])
import numpy as np
arr = np.arange(1,10)
# Check the array for even numbers
result = arr % 2 == 0
even_num_array = arr[result]
# Check the array for odd numbers
result = arr % 2 != 0
odd_num_array = arr[result]
print("Even array", even_num_array)
print("Odd array", odd_num_array)