Boolean Masking
Problem Statement
Use boolean conditions to filter NumPy arrays.
Background
Boolean indexing selects elements based on conditions:
arr[arr > 5] # All elements greater than 5
arr[arr % 2 == 0] # All even elements
Your Task
Write a function filter_array(arr, threshold) that returns a dictionary with:
- "above": Elements strictly greater than threshold (as list)
- "below_eq": Elements less than or equal to threshold (as list)
- "count_above": Count of elements above threshold
Example
arr = [1, 5, 3, 8, 2, 9, 4, 7], threshold = 5
{'above': [8, 9, 7], 'below_eq': [1, 5, 3, 2, 4], 'count_above': 3}- Inputs:
arris a 1D array of eight integers, , andthresholdis the number that every element is compared against. - The test: for each element , ask one yes/no question: is ? The answers, position by position, are no, no, no, yes, no, yes, no, yes.
above: keep the elements that answered yes, in their original order: . Order is preserved, not sorted, which is why sits between and .below_eq: the complement, every : . Notice the lands here, because is false; the two groups split the array with no overlap and no gaps ( elements).count_above: the number of yes answers, , a plain whole number.- Output:
{'above': [8, 9, 7], 'below_eq': [1, 5, 3, 2, 4], 'count_above': 3}, with both groups as ordinary Python lists. If no element exceeds the threshold,aboveis[]and the count is .
Constraints
- Use boolean indexing arr[condition]
- threshold will be a number