0
0
NumPydata~20 mins

Record arrays in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.