To create a record array from a list of individual records, you can use the numpy.rec.array()
function in NumPy. The rec.array()
function allows you to create a structured array where each element in the array corresponds to a record with multiple fields. Here’s an example:
import numpy as np # Define the individual records record1 = (1, "John", 25) record2 = (2, "Alice", 30) record3 = (3, "Bob", 28) # Create the record array records = np.rec.array([record1, record2, record3], dtype=[('id', int), ('name', object), ('age', int)]) print(records)
Output:
[(1, 'John', 25) (2, 'Alice', 30) (3, 'Bob', 28)]
In this example, we define three individual records as tuples: record1
, record2
, and record3
. Each record consists of multiple fields, such as ‘id’, ‘name’, and ‘age’.
We then use the np.rec.array()
function to create the record array records
. The dtype
parameter is used to specify the data type of each field in the record array. In this case, we define the data type as [('id', int), ('name', object), ('age', int)]
, which indicates that the ‘id’ and ‘age’ fields are of integer type, and the ‘name’ field is of an object type.
Run Code In Live & Test
Conclusion:
The resulting records
array is a structured array where each element represents a record with multiple fields. You can access individual fields using the field names, e.g., records['id']
, records['name']
, records['age']
, and perform operations and manipulations on the record array as needed.