0
0
NumPydata~20 mins

Practical uses of structured arrays in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Structured Arrays Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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'])
A[1 2]
B[2.5 3.5 4.5]
C['a' 'b']
D[2.5 3.5]
Attempts:
2 left
💡 Hint
Look at the dtype and which field is accessed by arr['y'].
data_output
intermediate
2: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))
A0
B1
C2
D3
Attempts:
2 left
💡 Hint
Count how many ages are greater than 30.
🔧 Debug
advanced
2: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')])
AValueError: could not convert string to float: 'abc'
BTypeError: data type mismatch
CSyntaxError: invalid syntax
DNo error, array created successfully
Attempts:
2 left
💡 Hint
Check the data types of the tuples and dtype fields.
🚀 Application
advanced
2: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')])
Astudents[np.lexsort((-students['age'], students['grade']))]
Bnp.sort(students, order=['grade', 'age'])
Cstudents[np.lexsort((students['age'], students['grade']))]
Dnp.sort(students, order=['grade', 'age'])[::-1]
Attempts:
2 left
💡 Hint
Use lexsort with negative age for descending order.
🧠 Conceptual
expert
2:00remaining
Why use structured arrays over regular arrays?
Which is the main advantage of using structured arrays in numpy compared to regular numpy arrays?
AThey compress data to use less memory than regular arrays.
BThey allow storing heterogeneous data types in one array with named fields.
CThey automatically parallelize computations for faster processing.
DThey support dynamic resizing like Python lists.
Attempts:
2 left
💡 Hint
Think about data types and field names.