Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a record array from a list of tuples.
NumPy
import numpy as np data = [(1, 'Alice', 3.5), (2, 'Bob', 4.0)] dtype = [('id', 'i4'), ('name', 'U10'), ('score', 'f4')] record_array = np.array(data, dtype=[1])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the data list as dtype instead of the dtype variable.
Forgetting to specify dtype when creating the array.
✗ Incorrect
We use the 'dtype' variable to specify the data types when creating the record array.
2fill in blank
mediumComplete the code to access the 'name' field from the record array.
NumPy
names = record_array[1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using double brackets which returns a subarray instead of a field.
Using string indexing which is invalid for record arrays.
✗ Incorrect
You can access fields in a record array using dot notation with the field name.
3fill in blank
hardFix the error in the code to create a record array with named fields.
NumPy
import numpy as np values = [(10, 'John', 2.5), (20, 'Jane', 3.0)] dtype = [('age', 'i4'), ('name', 'U5'), ('height', 'f4')] rec_arr = np.array(values, [1]=dtype)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'type' instead of 'dtype'.
Using 'dtypes' which is not recognized.
✗ Incorrect
The correct keyword argument to specify data types is 'dtype'.
4fill in blank
hardFill both blanks to create a record array and access the 'score' field.
NumPy
import numpy as np values = [(1, 'Ann', 4.2), (2, 'Ben', 3.8)] dtype = [('id', 'i4'), ('name', 'U10'), ('score', 'f4')] rec_arr = np.array([1], dtype=[2]) scores = rec_arr.score
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the data and dtype variables.
Using undefined variables for data or dtype.
✗ Incorrect
We pass the data list 'values' and the data type 'dtype' to create the record array.
5fill in blank
hardFill all three blanks to create a record array, filter by score > 3.5, and get names.
NumPy
import numpy as np values = [(1, 'Tom', 3.2), (2, 'Sue', 4.5), (3, 'Max', 3.8)] dtype = [('id', 'i4'), ('name', 'U10'), ('score', 'f4')] rec_arr = np.array([1], dtype=[2]) high_scores = rec_arr[rec_arr.score [3] 3.5] names = high_scores.name
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' for filtering.
Using wrong variable names for data or dtype.
✗ Incorrect
We create the record array from 'values' and 'dtype', then filter scores greater than 3.5 using '>'.