0
0
NumPydata~20 mins

np.where() for conditional selection in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
np.where() Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[ 0 0 0 25 30]
B[10 15 20 25 30]
C[10 15 20 0 0]
D[ 0 15 20 25 30]
Attempts:
2 left
💡 Hint
np.where(condition, x, y) returns elements from x where condition is True, else from y.
data_output
intermediate
1: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)
A(2, 3)
B(6,)
C(3, 2)
D(3,)
Attempts:
2 left
💡 Hint
np.where returns an array with the same shape as the input when used with three arguments.
🔧 Debug
advanced
1: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)
ANo error, prints indices where condition is True
BSyntaxError: invalid syntax
CValueError: operands could not be broadcast together
DTypeError: where() missing required argument 'y' (pos 3)
Attempts:
2 left
💡 Hint
np.where can be used with one or three arguments. With one argument, it returns indices.
🚀 Application
advanced
2: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])
Anp.where(arr > 0, arr, 0)
Bnp.where(arr < 0, 0, arr)
Cnp.where(arr <= 0, 0, arr)
Dnp.where(arr == 0, 0, arr)
Attempts:
2 left
💡 Hint
Replace values less than zero with zero, keep others unchanged.
🧠 Conceptual
expert
2: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)
A['even' 'even' 'div3' 'even' 'odd']
B['odd' 'even' 'odd' 'even' 'odd']
C['odd' 'even' 'div3' 'odd' 'odd']
D['odd' 'even' 'div3' 'even' 'odd']
Attempts:
2 left
💡 Hint
np.where can be nested to check multiple conditions in order.