0
0
NumPydata~10 mins

np.where() for conditional selection in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to select elements greater than 5 using np.where().

NumPy
import numpy as np
arr = np.array([3, 7, 1, 9, 4])
result = np.where(arr [1] 5)
print(result)
Drag options to blanks, or click blank then click option'
A!=
B<
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > will select wrong elements.
Using == will only select elements exactly equal to 5.
2fill in blank
medium

Complete the code to replace values less than 4 with 0 using np.where().

NumPy
import numpy as np
arr = np.array([2, 5, 3, 7, 1])
new_arr = np.where(arr [1] 4, 0, arr)
print(new_arr)
Drag options to blanks, or click blank then click option'
A>
B<
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using > will replace wrong elements.
Forgetting to provide the else part keeps all elements unchanged.
3fill in blank
hard

Fix the error in the code to select elements equal to 10 using np.where().

NumPy
import numpy as np
arr = np.array([10, 5, 10, 3, 10])
indices = np.where(arr [1] 10)
print(indices)
Drag options to blanks, or click blank then click option'
A===
B=
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using single = causes syntax error.
Using === is invalid in Python.
4fill in blank
hard

Fill both blanks to create a new array where values greater than 3 are replaced by 1, else 0.

NumPy
import numpy as np
arr = np.array([2, 4, 1, 5, 3])
new_arr = np.where(arr [1] 3, [2], 0)
print(new_arr)
Drag options to blanks, or click blank then click option'
A>
B1
C<
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > selects wrong elements.
Replacing with 0 instead of 1 changes the output.
5fill in blank
hard

Fill all three blanks to create a new array where values less than 5 are replaced by 0, values equal to 5 by 5, else by 10.

NumPy
import numpy as np
arr = np.array([3, 5, 7, 2, 5])
new_arr = np.where(arr [1] 5, 0, np.where(arr [2] 5, [3], 10))
print(new_arr)
Drag options to blanks, or click blank then click option'
A<
B==
C5
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up < and == operators.
Using wrong replacement values changes the output.