Challenge - 5 Problems
Boolean Indexing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Boolean Indexing on a NumPy Array
What is the output of this code snippet using Boolean indexing on a NumPy array?
NumPy
import numpy as np arr = np.array([10, 15, 20, 25, 30]) result = arr[arr > 20] print(result)
Attempts:
2 left
💡 Hint
Remember, Boolean indexing selects elements where the condition is True.
✗ Incorrect
The condition arr > 20 selects elements greater than 20, which are 25 and 30.
❓ data_output
intermediate2:00remaining
Number of Elements Selected by Boolean Indexing
How many elements are selected by the Boolean indexing in this code?
NumPy
import numpy as np arr = np.array([5, 12, 17, 9, 3, 21]) selected = arr[(arr >= 10) & (arr < 20)] print(len(selected))
Attempts:
2 left
💡 Hint
Count elements between 10 (inclusive) and 20 (exclusive).
✗ Incorrect
Elements satisfying (arr >= 10) & (arr < 20): 12 and 17 (9 < 10 excluded, 21 >= 20 excluded), so 2 elements.
❓ Predict Output
advanced2:00remaining
Output of Boolean Indexing with Multiple Conditions
What is the output of this code using Boolean indexing with multiple conditions?
NumPy
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) result = arr[(arr % 2 == 0) | (arr > 7)] print(result)
Attempts:
2 left
💡 Hint
Select elements that are even or greater than 7.
✗ Incorrect
Elements that are even: 2,4,6,8; elements greater than 7: 8,9; combined unique elements: 2,4,6,8,9.
🔧 Debug
advanced2:00remaining
Identify the Error in Boolean Indexing Code
What error does this code raise when using Boolean indexing?
NumPy
import numpy as np arr = np.array([1, 2, 3, 4, 5]) mask = arr > 3 result = arr[mask == True] print(result)
Attempts:
2 left
💡 Hint
Check if comparing Boolean array to True affects indexing.
✗ Incorrect
mask == True returns the same Boolean array, so indexing works and outputs [4 5].
🚀 Application
expert3:00remaining
Filter Rows in 2D Array Using Boolean Indexing
Given this 2D NumPy array, which option correctly selects rows where the second column is less than 5?
NumPy
import numpy as np arr = np.array([[1, 4, 7], [2, 5, 8], [3, 3, 9], [4, 6, 10]]) result = ??? print(result)
Attempts:
2 left
💡 Hint
Use Boolean indexing on rows based on the second column values.
✗ Incorrect
arr[:, 1] selects the second column; arr[:, 1] < 5 creates a Boolean mask for rows; indexing arr with this mask selects rows where second column < 5.