0
0
NumPydata~10 mins

np.choose() 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 from arrays using np.choose.

NumPy
import numpy as np
choices = [np.array([1, 2, 3]), np.array([4, 5, 6])]
index = np.array([0, 1, 0])
result = np.choose([1], choices)
print(result)
Drag options to blanks, or click blank then click option'
Anp.array
Bchoices
Cresult
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the choices list as the first argument instead of the index array.
Confusing the order of arguments in np.choose.
2fill in blank
medium

Complete the code to create an index array for np.choose based on a condition.

NumPy
import numpy as np
arr = np.array([10, 20, 30, 40])
index = (arr > 25).astype([1])
print(index)
Drag options to blanks, or click blank then click option'
Afloat
Bint
Cbool
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using boolean type directly without conversion.
Using float or string types which cause errors.
3fill in blank
hard

Fix the error in the np.choose call to select elements correctly.

NumPy
import numpy as np
choices = [np.array([100, 200, 300]), np.array([400, 500, 600])]
index = np.array([1, 0, 1])
result = np.choose([1], choices)
print(result)
Drag options to blanks, or click blank then click option'
Aindex
Bchoices
Cnp.array
Dresult
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of arguments in np.choose.
Passing the choices list as the first argument.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that uses np.choose to select values based on a condition.

NumPy
import numpy as np
values = {'a': 5, 'b': 15, 'c': 25}
index = np.array([0 if v < 10 else 1 for v in values.values()])
choices = [np.array([10, 20, 30]), np.array([40, 50, 60])]
result = {k: np.choose([1], choices)[i] for i, k in enumerate(values.keys()) if values[k] [2] 20}
print(result)
Drag options to blanks, or click blank then click option'
Aindex
Bvalues
C<
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable for the index array.
Using the wrong comparison operator causing wrong filtering.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that uses np.choose to select values and filters keys based on a condition.

NumPy
import numpy as np
scores = {'x': 8, 'y': 15, 'z': 22}
index = np.array([0 if s [1] 10 else 1 for s in scores.values()])
choices = [np.array([100, 200, 300]), np.array([400, 500, 600])]
result = [2]: np.choose(index, choices)[i] for i, [2] in enumerate(scores.keys()) if scores[[2]] [3] 20}
print(result)
Drag options to blanks, or click blank then click option'
A<
Bv
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators.
Using incorrect variable names in the dictionary comprehension.