What is the output of the following code?
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'])
Remember that record array fields keep their original data types, including byte strings.
The field 'foo' contains integers, so printing rec.foo outputs an integer array. The field 'baz' is a byte string type, so printing rec['baz'] outputs byte strings.
Given the record array below, how many elements remain after filtering where age > 30?
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))
Count how many ages are greater than 30.
Only 'Bob' (35) and 'Charlie' (40) have ages greater than 30, so 2 elements remain.
What error does the following code raise?
import numpy as np rec = np.rec.array([(1, 2.0), (3, 4.0)], dtype=[('x', 'i4'), ('y', 'f4')]) rec.x = [10, 20, 30]
Check if the length of the assigned list matches the record array length.
The record array has length 2, but the list assigned has length 3, causing a ValueError due to shape mismatch.
You have a structured array arr with dtype [('a', 'i4'), ('b', 'f4')]. Which code correctly converts it to a record array?
import numpy as np arr = np.array([(1, 2.0), (3, 4.0)], dtype=[('a', 'i4'), ('b', 'f4')])
Use the view method to change the array type without copying data.
Using arr.view(np.recarray) creates a record array view of the structured array without copying data. Option D creates a new record array but copies data. Option D is invalid dtype usage. Option D creates an empty record array.
Which statement best explains the advantage of using NumPy record arrays over structured arrays?
Think about how you access data fields in each array type.
Record arrays allow accessing fields using dot notation (e.g., rec.field), which can make code easier to write and read. Structured arrays require dictionary-like access (e.g., arr['field']). Memory usage and string handling are similar, and both support multi-dimensional fields.