Challenge - 5 Problems
np.where() Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.where() with simple condition
What is the output of this code snippet?
NumPy
import numpy as np arr = np.array([10, 15, 20, 25, 30]) result = np.where(arr > 20, arr, 0) print(result)
Attempts:
2 left
💡 Hint
np.where(condition, x, y) returns elements from x where condition is True, else from y.
✗ Incorrect
The condition arr > 20 is True for elements 25 and 30 only. So, np.where returns those elements, and 0 for others.
❓ data_output
intermediate1:30remaining
Resulting array shape after np.where() with condition
Given the code below, what is the shape of the resulting array?
NumPy
import numpy as np arr = np.array([[1, 2], [3, 4], [5, 6]]) result = np.where(arr % 2 == 0, arr, -1) print(result.shape)
Attempts:
2 left
💡 Hint
np.where returns an array with the same shape as the input when used with three arguments.
✗ Incorrect
The input array arr has shape (3, 2). Using np.where with condition and two arrays returns an array of the same shape.
🔧 Debug
advanced1:30remaining
Identify the error in np.where usage
What error does this code raise?
NumPy
import numpy as np arr = np.array([1, 2, 3, 4]) result = np.where(arr > 2) print(result)
Attempts:
2 left
💡 Hint
np.where can be used with one or three arguments. With one argument, it returns indices.
✗ Incorrect
When np.where is called with only the condition, it returns the indices where the condition is True. No error occurs.
🚀 Application
advanced2:00remaining
Using np.where() to replace negative values
Given the array below, which option correctly replaces all negative values with zero using np.where()?
NumPy
import numpy as np arr = np.array([3, -1, 5, -7, 2])
Attempts:
2 left
💡 Hint
Replace values less than zero with zero, keep others unchanged.
✗ Incorrect
Option B replaces all elements less than zero with 0, keeping others as is. Others either replace wrong values or miss negatives.
🧠 Conceptual
expert2:30remaining
Understanding np.where() output with multiple conditions
Consider this code snippet. What is the output of
result?NumPy
import numpy as np arr = np.array([1, 2, 3, 4, 5]) result = np.where(arr % 2 == 0, 'even', np.where(arr % 3 == 0, 'div3', 'odd')) print(result)
Attempts:
2 left
💡 Hint
np.where can be nested to check multiple conditions in order.
✗ Incorrect
For each element: if divisible by 2, label 'even'; else if divisible by 3, label 'div3'; else 'odd'.