Challenge - 5 Problems
Structured Arrays Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing fields in a structured array
What is the output of this code snippet that creates a structured array and accesses one of its fields?
NumPy
import numpy as np arr = np.array([(1, 2.5, 'a'), (2, 3.5, 'b')], dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'U1')]) print(arr['y'])
Attempts:
2 left
💡 Hint
Look at the dtype and which field is accessed by arr['y'].
✗ Incorrect
The structured array has fields 'x', 'y', and 'z'. Accessing arr['y'] returns the array of values in the 'y' field, which are floats 2.5 and 3.5.
❓ data_output
intermediate2:00remaining
Number of records after filtering a structured array
Given this structured array, how many records remain after filtering for 'age' > 30?
NumPy
import numpy as np people = np.array([(25, 'Alice'), (35, 'Bob'), (40, 'Charlie')], dtype=[('age', 'i4'), ('name', 'U10')]) adults = people[people['age'] > 30] print(len(adults))
Attempts:
2 left
💡 Hint
Count how many ages are greater than 30.
✗ Incorrect
Only Bob (35) and Charlie (40) have age > 30, so 2 records remain.
🔧 Debug
advanced2:00remaining
Identify the error in structured array creation
What error does this code raise when trying to create a structured array?
NumPy
import numpy as np arr = np.array([(1, 2.5), (2, 'abc')], dtype=[('a', 'i4'), ('b', 'f4')])
Attempts:
2 left
💡 Hint
Check the data types of the tuples and dtype fields.
✗ Incorrect
The second tuple has a string 'abc' where a float is expected, causing a ValueError during conversion.
🚀 Application
advanced2:00remaining
Using structured arrays to sort by multiple fields
Which option correctly sorts this structured array first by 'grade' ascending, then by 'age' descending?
NumPy
import numpy as np students = np.array([(90, 20), (90, 22), (85, 21)], dtype=[('grade', 'i4'), ('age', 'i4')])
Attempts:
2 left
💡 Hint
Use lexsort with negative age for descending order.
✗ Incorrect
np.lexsort sorts by keys from last to first. Using -students['age'] sorts age descending, and students['grade'] ascending.
🧠 Conceptual
expert2:00remaining
Why use structured arrays over regular arrays?
Which is the main advantage of using structured arrays in numpy compared to regular numpy arrays?
Attempts:
2 left
💡 Hint
Think about data types and field names.
✗ Incorrect
Structured arrays let you store different data types in one array with named fields, unlike regular arrays which are homogeneous.