Bird
Raised Fist0
NumPydata~20 mins

Record arrays 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
🎖️
Record Array Master
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 record array

What is the output of the following code?

NumPy
import numpy as np

rec = np.rec.array([(1, 2.0, 'Hello'), (2, 3.0, 'World')],
                  dtype=[('foo', 'i4'), ('bar', 'f4'), ('baz', 'a5')])

print(rec.foo)
print(rec['baz'])
A
[1 2]
[b'Hello' b'World']
B
[1 2]
['Hello' 'World']
C
[1. 2.]
[b'Hello' b'World']
D
[1 2]
[b'Hello' b'World' b'!']
Attempts:
2 left
💡 Hint

Remember that record array fields keep their original data types, including byte strings.

❓ data_output
intermediate
1:30remaining
Number of elements in a record array after filtering

Given the record array below, how many elements remain after filtering where age > 30?

NumPy
import numpy as np

rec = np.rec.array([(25, 'Alice'), (35, 'Bob'), (40, 'Charlie')],
                  dtype=[('age', 'i4'), ('name', 'U10')])

filtered = rec[rec.age > 30]

print(len(filtered))
A0
B1
C2
D3
Attempts:
2 left
💡 Hint

Count how many ages are greater than 30.

🔧 Debug
advanced
1:30remaining
Identify the error in record array field assignment

What error does the following code raise?

NumPy
import numpy as np

rec = np.rec.array([(1, 2.0), (3, 4.0)], dtype=[('x', 'i4'), ('y', 'f4')])
rec.x = [10, 20, 30]
AValueError: setting an array element with a sequence.
BIndexError: too many indices for array
CAttributeError: can't set attribute
DTypeError: invalid type assignment
Attempts:
2 left
💡 Hint

Check if the length of the assigned list matches the record array length.

🚀 Application
advanced
2:00remaining
Create a record array from a structured array

You have a structured array arr with dtype [('a', 'i4'), ('b', 'f4')]. Which code correctly converts it to a record array?

NumPy
import numpy as np

arr = np.array([(1, 2.0), (3, 4.0)], dtype=[('a', 'i4'), ('b', 'f4')])
Arec = np.recarray(arr.shape, dtype=arr.dtype)
Brec = np.rec.array(arr)
Crec = np.array(arr, dtype=np.recarray)
Drec = arr.view(np.recarray)
Attempts:
2 left
💡 Hint

Use the view method to change the array type without copying data.

🧠 Conceptual
expert
1:30remaining
Why use record arrays instead of structured arrays?

Which statement best explains the advantage of using NumPy record arrays over structured arrays?

ARecord arrays support multi-dimensional fields, unlike structured arrays.
BRecord arrays allow accessing fields as attributes, making code more readable and concise.
CRecord arrays automatically convert all string fields to Unicode.
DRecord arrays use less memory than structured arrays for the same data.
Attempts:
2 left
💡 Hint

Think about how you access data fields in each array type.

Practice

(1/5)
1. What is the main advantage of using a record array in numpy?
easy
A. It speeds up numerical calculations on large arrays.
B. It automatically sorts data based on values.
C. It allows storing different data types in one array with named fields.
D. It compresses data to save memory.

Solution

  1. Step 1: Understand record arrays

    Record arrays let you store mixed data types in one numpy array by using named fields.
  2. Step 2: Compare options

    Only It allows storing different data types in one array with named fields. correctly describes this feature. Others describe unrelated features.
  3. Final Answer:

    It allows storing different data types in one array with named fields. -> Option C
  4. Quick Check:

    Record arrays = mixed types + named fields [OK]
Hint: Remember: record arrays hold mixed types with names [OK]
Common Mistakes:
  • Confusing record arrays with regular numeric arrays
  • Thinking record arrays sort data automatically
  • Assuming record arrays compress data
2. Which of the following is the correct way to create a numpy record array with fields 'name' (string) and 'age' (integer)?
easy
A. np.rec.array([("Alice", 25), ("Bob", 30)], dtype=[('name', 'U10'), ('age', 'i4')])
B. np.array([("Alice", 25), ("Bob", 30)], dtype=[('name', 'i4'), ('age', 'U10')])
C. np.rec.array(["Alice", 25, "Bob", 30], dtype=[('name', 'U10'), ('age', 'i4')])
D. np.rec.array([(25, "Alice"), (30, "Bob")], dtype=[('name', 'U10'), ('age', 'i4')])

Solution

  1. Step 1: Check data and dtype matching

    np.rec.array([("Alice", 25), ("Bob", 30)], dtype=[('name', 'U10'), ('age', 'i4')]) matches tuples of (string, int) with dtype [('name', 'U10'), ('age', 'i4')].
  2. Step 2: Validate other options

    np.array([("Alice", 25), ("Bob", 30)], dtype=[('name', 'i4'), ('age', 'U10')]) swaps types incorrectly; C has wrong input format; A swaps field order.
  3. Final Answer:

    np.rec.array([("Alice", 25), ("Bob", 30)], dtype=[('name', 'U10'), ('age', 'i4')]) -> Option A
  4. Quick Check:

    Data matches dtype order and types [OK]
Hint: Match tuple order with dtype fields exactly [OK]
Common Mistakes:
  • Swapping field order between data and dtype
  • Using wrong data types in dtype
  • Passing flat list instead of list of tuples
3. What will be the output of the following code?
import numpy as np
rec = np.rec.array([(1, 2.5), (3, 4.5)], dtype=[('x', 'i4'), ('y', 'f4')])
print(rec.x + rec.y)
medium
A. TypeError
B. [3 7]
C. [1 3]
D. [3.5 7.5]

Solution

  1. Step 1: Understand data and fields

    rec.x is integer array [1, 3], rec.y is float array [2.5, 4.5].
  2. Step 2: Add integer and float arrays element-wise

    Adding [1, 3] + [2.5, 4.5] results in [3.5, 7.5] as floats.
  3. Final Answer:

    [3.5 7.5] -> Option D
  4. Quick Check:

    1+2.5=3.5 and 3+4.5=7.5 [OK]
Hint: Adding int and float fields results in float array [OK]
Common Mistakes:
  • Expecting integer output instead of float
  • Confusing field names or types
  • Thinking addition causes error
4. Identify the error in this code snippet:
import numpy as np
rec = np.rec.array([(1, 'a'), (2, 'b')], dtype=[('num', 'i4'), ('char', 'U1')])
print(rec.num + rec.char)
medium
A. You cannot add integer and string fields directly.
B. The dtype specification is incorrect.
C. The data tuples have wrong length.
D. The record array must be created with np.array, not np.rec.array.

Solution

  1. Step 1: Analyze the operation

    rec.num is integer array, rec.char is string array.
  2. Step 2: Check addition of int and string

    Adding int + string causes a TypeError in numpy.
  3. Final Answer:

    You cannot add integer and string fields directly. -> Option A
  4. Quick Check:

    int + string = TypeError [OK]
Hint: Cannot add numbers and strings directly in numpy [OK]
Common Mistakes:
  • Assuming dtype is wrong instead of operation
  • Thinking np.rec.array is incorrect here
  • Ignoring type mismatch in addition
5. You have a numpy record array rec with fields 'id' (int), 'score' (float), and 'passed' (bool). How do you create a new record array containing only records where passed is True and score is above 80?
hard
A. rec[rec.passed or rec.score > 80]
B. rec[(rec.passed) & (rec.score > 80)]
C. rec[rec.passed and rec.score > 80]
D. rec[(rec.passed) | (rec.score > 80)]

Solution

  1. Step 1: Understand filtering syntax

    Use boolean indexing with & for element-wise AND, parentheses needed.
  2. Step 2: Evaluate options

    rec[(rec.passed) & (rec.score > 80)] correctly uses (rec.passed) & (rec.score > 80). Options B and C use Python 'or'/'and' which don't work element-wise. rec[(rec.passed) | (rec.score > 80)] uses | (OR) instead of AND.
  3. Final Answer:

    rec[(rec.passed) & (rec.score > 80)] -> Option B
  4. Quick Check:

    Use & with parentheses for element-wise AND [OK]
Hint: Use & with parentheses for element-wise conditions [OK]
Common Mistakes:
  • Using 'and' or 'or' instead of '&' or '|' for arrays
  • Forgetting parentheses around conditions
  • Using | instead of & for AND condition