0
0
NumPydata~10 mins

Practical uses of structured arrays 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 create a structured array with fields 'name' and 'age'.

NumPy
import numpy as np

people = np.array([('Alice', 25), ('Bob', 30)], dtype=[1])
Drag options to blanks, or click blank then click option'
A[('name', 'U10'), ('age', 'i4')]
B[('name', 'S10'), ('age', 'f4')]
C[('name', 'U20'), ('age', 'f8')]
D[('name', 'U5'), ('age', 'i2')]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong dtype format like a list of strings instead of tuples.
Choosing float type for age instead of integer.
2fill in blank
medium

Complete the code to access the 'age' field from the structured array.

NumPy
ages = people[1]
Drag options to blanks, or click blank then click option'
A['age']
B.age
C[1]
D['name']
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation which raises an error.
Accessing by index which returns a row, not a field.
3fill in blank
hard

Fix the error in the code to filter people older than 27.

NumPy
older = people[people['age'] [1] 27]
Drag options to blanks, or click blank then click option'
A<=
B<
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than or equal operator which filters the wrong group.
Using equality operator which filters only age 27.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension mapping names to ages for people younger than 30.

NumPy
young_dict = {person[1]: person[2] for person in people if person['age'] < 30}
Drag options to blanks, or click blank then click option'
A['name']
B['age']
C.name
D.age
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation which causes an error.
Mixing up 'name' and 'age' fields.
5fill in blank
hard

Fill all three blanks to create a new structured array with uppercase names and ages increased by 1.

NumPy
new_people = np.array([(person[1].upper(), person[2] + [3]) for person in people], dtype=people.dtype)
Drag options to blanks, or click blank then click option'
A['name']
B['age']
C1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation for fields.
Adding 2 instead of 1 to age.
Forgetting to use upper() on the name.