Record arrays let you store different types of data together in one array. This helps when you want to keep related information like names, ages, and scores in one place.
Record arrays in NumPy
import numpy as np # Define a record array with fields and types record_array = np.rec.array( [(value1, value2, ...), (value1, value2, ...)], dtype=[('field1', type1), ('field2', type2), ...] )
The dtype defines the name and type of each field.
You can access fields by name like record_array.field1.
import numpy as np # Empty record array with defined fields empty_records = np.rec.array([], dtype=[('name', 'U10'), ('age', 'i4')]) print(empty_records)
import numpy as np # Record array with one element one_record = np.rec.array([('Alice', 30)], dtype=[('name', 'U10'), ('age', 'i4')]) print(one_record) print(one_record.name) print(one_record.age)
import numpy as np # Record array with multiple elements people = np.rec.array([ ('Bob', 25), ('Carol', 40), ('Dave', 35) ], dtype=[('name', 'U10'), ('age', 'i4')]) print(people) print(people.name) print(people.age)
import numpy as np # Accessing last element print(people[-1]) print(people[-1].name) print(people[-1].age)
This program creates a record array with three people, prints it, adds a new person, and prints the updated array. Then it shows how to access each field by name.
import numpy as np # Create a record array with three people people = np.rec.array([ ('Alice', 28, 5.5), ('Bob', 34, 6.0), ('Carol', 22, 5.7) ], dtype=[('name', 'U10'), ('age', 'i4'), ('height', 'f4')]) print("Before adding new record:") print(people) # Add a new record by creating a new array with one more element new_person = np.rec.array([('Dave', 30, 5.9)], dtype=people.dtype) people = np.concatenate((people, new_person)) print("\nAfter adding new record:") print(people) # Access fields by name print("\nNames:", people.name) print("Ages:", people.age) print("Heights:", people.height)
Time complexity for accessing a field is O(1) because fields are stored separately internally.
Space complexity is similar to normal numpy arrays but slightly more due to field names.
Common mistake: Trying to add records by appending directly to the record array. Instead, create a new array and concatenate.
Use record arrays when you want structured data with named fields and mixed types. Use pandas DataFrame if you need more complex table operations.
Record arrays store mixed data types in one numpy array with named fields.
You can access data by field names like array.field.
They are useful for simple structured data and fast access in numpy.