0
0
NumPydata~20 mins

Accessing fields by name in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Field Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Accessing a single field by name in a structured NumPy array
What is the output of this code snippet?
NumPy
import numpy as np

arr = np.array([(1, 2.0), (3, 4.0)], dtype=[('x', 'i4'), ('y', 'f4')])
result = arr['y']
print(result)
A[1 3]
B[2. 4.]
C[(1, 2.) (3, 4.)]
D[2 4]
Attempts:
2 left
💡 Hint
Accessing a field by name returns an array of that field's values.
data_output
intermediate
2:00remaining
Shape of field extracted from structured array
Given this structured array, what is the shape of the extracted field 'b'?
NumPy
import numpy as np

arr = np.array([(1, (2, 3)), (4, (5, 6))], dtype=[('a', 'i4'), ('b', 'i4', (2,))])
field_b = arr['b']
print(field_b.shape)
A(2, 2)
B(2,)
C(2, 1)
D(1, 2)
Attempts:
2 left
💡 Hint
The field 'b' is a 2-element integer array per record, and there are 2 records.
🔧 Debug
advanced
2:00remaining
Identify the error when accessing a non-existent field
What error does this code raise?
NumPy
import numpy as np

arr = np.array([(1, 2)], dtype=[('x', 'i4'), ('y', 'i4')])
print(arr['z'])
AIndexError: index out of range
BTypeError: unhashable type: 'slice'
CAttributeError: 'numpy.ndarray' object has no attribute 'z'
DKeyError: 'z'
Attempts:
2 left
💡 Hint
Accessing a field by a name not in the dtype raises a KeyError.
🚀 Application
advanced
2:00remaining
Extracting multiple fields and combining them
Given this structured array, which option correctly creates a new array combining fields 'name' and 'age' as a list of tuples?
NumPy
import numpy as np

arr = np.array([('Alice', 25), ('Bob', 30)], dtype=[('name', 'U10'), ('age', 'i4')])
Anp.array((arr['name'], arr['age']))
Barr[['name', 'age']].tolist()
Clist(zip(arr['name'], arr['age']))
D[arr['name'], arr['age']]
Attempts:
2 left
💡 Hint
Use zip to pair elements from two arrays into tuples.
🧠 Conceptual
expert
2:00remaining
Understanding memory layout when accessing fields by name
When you access a field by name in a structured NumPy array, what best describes the memory layout of the returned array?
AIt is a view of the original array sharing the same memory.
BIt is a new array with data copied and reshaped.
CIt is a deep copy with independent memory.
DIt is a list of Python objects extracted from the array.
Attempts:
2 left
💡 Hint
Accessing a field returns a view, not a copy, unless explicitly copied.