Bird
Raised Fist0
NumPydata~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the correct way to access the field named 'age' from a NumPy structured array data?
easy
A. data['age']
B. data.age()
C. data[age]
D. data.get('age')

Solution

  1. Step 1: Understand structured array field access

    In NumPy, fields in structured arrays are accessed using square brackets with the field name as a string.
  2. Step 2: Identify correct syntax for field access

    The syntax data['age'] correctly accesses the 'age' field. Other options use incorrect methods or syntax.
  3. Final Answer:

    data['age'] -> Option A
  4. Quick Check:

    Field access uses square brackets with field name [OK]
Hint: Use square brackets with field name as string [OK]
Common Mistakes:
  • Using unquoted field name like data[age]
  • Calling field as a method like data.age()
  • Using data.get() which is not valid for structured arrays
2. Which of the following is the correct syntax to create a NumPy structured array with fields 'name' (string) and 'score' (integer)?
easy
A. np.array([('Alice', 90), ('Bob', 85)], dtype=[('name', 'U10'), ('score', 'i4')])
B. np.array([('Alice', 90), ('Bob', 85)], dtype={name: 'U10', score: 'i4'})
C. np.array([('Alice', 90), ('Bob', 85)], dtype=[{name: 'U10'}, {score: 'i4'}])
D. np.array([('Alice', 90), ('Bob', 85)], dtype=('name', 'U10', 'score', 'i4'))

Solution

  1. Step 1: Understand dtype format for structured arrays

    The dtype should be a list of tuples, each tuple with field name and data type.
  2. Step 2: Match correct dtype syntax

    np.array([('Alice', 90), ('Bob', 85)], dtype=[('name', 'U10'), ('score', 'i4')]) uses the correct list of tuples format: [('name', 'U10'), ('score', 'i4')]. Other options use incorrect dtype formats.
  3. Final Answer:

    np.array([('Alice', 90), ('Bob', 85)], dtype=[('name', 'U10'), ('score', 'i4')]) -> Option A
  4. Quick Check:

    dtype as list of (name, type) tuples [OK]
Hint: Use list of (field, type) tuples for dtype [OK]
Common Mistakes:
  • Using dict instead of list of tuples for dtype
  • Passing dtype as a flat tuple instead of list
  • Incorrect nested dict inside dtype list
3. Given the structured array arr = np.array([(1, 2.5), (3, 4.5)], dtype=[('x', 'i4'), ('y', 'f4')]), what is the output of arr['y']?
medium
A. [1. 3.]
B. [2.5 4.5]
C. [(1, 2.5) (3, 4.5)]
D. Error: field 'y' not found

Solution

  1. Step 1: Understand the structured array fields

    The array has two fields: 'x' (integers) and 'y' (floats). The values for 'y' are 2.5 and 4.5.
  2. Step 2: Access the 'y' field values

    Using arr['y'] returns an array of the 'y' values: [2.5, 4.5].
  3. Final Answer:

    [2.5 4.5] -> Option B
  4. Quick Check:

    arr['y'] returns float values [OK]
Hint: Access field returns array of that field's values [OK]
Common Mistakes:
  • Confusing field 'x' values with 'y'
  • Expecting full tuples instead of single field array
  • Assuming error due to wrong field name
4. What is wrong with this code snippet?
arr = np.array([(1, 2), (3, 4)], dtype=[('id', 'i4'), ('b', 'i4')])
print(arr.a)
medium
A. It raises a TypeError because dtype is incorrect.
B. It raises a SyntaxError due to missing quotes around field names.
C. It prints the array correctly without errors.
D. It raises an AttributeError because fields are accessed with brackets, not dot notation.

Solution

  1. Step 1: Check field access method

    NumPy structured array fields must be accessed using square brackets with the field name as a string, not dot notation.
  2. Step 2: Identify error from dot notation

    Using arr.a causes AttributeError because 'a' is not an attribute but a field name.
  3. Final Answer:

    It raises an AttributeError because fields are accessed with brackets, not dot notation. -> Option D
  4. Quick Check:

    Use arr['a'], not arr.a [OK]
Hint: Use brackets, not dot, to access fields [OK]
Common Mistakes:
  • Using dot notation to access fields
  • Assuming dtype syntax error
  • Expecting code to print without error
5. You have a structured array data with fields 'name' (string), 'age' (int), and 'score' (float). How do you create a new array containing only the 'name' and 'score' fields?
hard
A. data['name']['score']
B. data[['name'], ['score']]
C. data[['name', 'score']]
D. data.get(['name', 'score'])

Solution

  1. Step 1: Understand field selection syntax

    To select multiple fields, use a list of field names inside double square brackets: data[['field1', 'field2']].
  2. Step 2: Apply correct syntax to select 'name' and 'score'

    Using data[['name', 'score']] returns a new structured array with only those fields.
  3. Final Answer:

    data[['name', 'score']] -> Option C
  4. Quick Check:

    Use double brackets with list of fields [OK]
Hint: Use double brackets with list of fields to select multiple [OK]
Common Mistakes:
  • Chaining field accesses like data['name']['score']
  • Passing separate lists for each field
  • Using .get() method which does not exist