0
0
NumPydata~20 mins

Creating structured arrays in NumPy - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Structured Arrays Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a structured array creation
What is the output of this code that creates a structured array with fields 'name' and 'age'?
NumPy
import numpy as np

person = np.array([('Alice', 25), ('Bob', 30)], dtype=[('name', 'U10'), ('age', 'i4')])
print(person)
A])03 ,'boB'( )52 ,'ecilA'([
B[('Alice', '25') ('Bob', '30')]
C[('Alice', 25) ('Bob', 30)]
D[('Alice', 25) ('Bob', 30) ('Charlie', 35)]
Attempts:
2 left
💡 Hint
Look at the dtype and how the values are stored as integers or strings.
data_output
intermediate
1:30remaining
Number of elements in a structured array
How many elements are in this structured array?
NumPy
import numpy as np

arr = np.array([(1, 2.5), (3, 4.5), (5, 6.5)], dtype=[('x', 'i4'), ('y', 'f4')])
print(len(arr))
A1
B2
C6
D3
Attempts:
2 left
💡 Hint
Count the number of tuples in the array creation.
🔧 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), (3, '4.5')], dtype=[('x', 'i4'), ('y', 'f4')])
AValueError: could not convert string to float: '4.5'
BTypeError: data type mismatch
CSyntaxError: invalid syntax
DNo error, array created successfully
Attempts:
2 left
💡 Hint
Check the data types and the values provided for each field.
🚀 Application
advanced
1:30remaining
Accessing fields in a structured array
Given this structured array, what is the output of printing arr['age']?
NumPy
import numpy as np

arr = np.array([('John', 28), ('Jane', 32)], dtype=[('name', 'U10'), ('age', 'i4')])
print(arr['age'])
A[('John', 28) ('Jane', 32)]
B[28 32]
C['John' 'Jane']
D[28, 32]
Attempts:
2 left
💡 Hint
Accessing a field returns an array of that field's values.
🧠 Conceptual
expert
2:30remaining
Memory layout of structured arrays
Which statement about the memory layout of numpy structured arrays is TRUE?
AStructured arrays store data as a single contiguous block with fields laid out in order, enabling efficient memory use.
BEach field in a structured array is stored in a separate numpy array internally.
CStructured arrays cannot store mixed data types in the same array.
DStructured arrays store all fields contiguously in memory, allowing fast access to any field.
Attempts:
2 left
💡 Hint
Think about how numpy stores data for performance and memory efficiency.