numpy.fromrecords()method is a powerful tool in the NumPy library that allows you to create structured arrays from a sequence of tuples or other array-like objects.
Let's understand the help of an example:
Pythonimportnumpyasnp# Define a list of recordsrecords=[(1,'Alice',25.5),(2,'Bob',30.0),(3,'Charlie',28.0)]# Define the data typedtype=[('id','i4'),('name','U10'),('age','f4')]# Create the structured arraystructured_array=np.fromrecords(records,dtype=dtype)print(structured_array)
Output:
[(1, 'Alice', 25.5) (2, 'Bob', 30. ) (3, 'Charlie', 28. )]
Syntax of Numpy fromrecords():
numpy.fromrecords(recList, dtype=None, shape=None, aligned=False, byteorder=None)
Parameters:
recList
: A list oftuples or structured data to be converted into a structuredNumPy array.dtype
(optional): The data type of the resulting structured array. If not provided, NumPy will infer the type from the input data.shape
(optional): Shape of the output array. Defaults to one-dimensional.aligned
(optional):IfTrue
, aligns fields to their natural alignment.byteorder
(optional): Specifies the byte order of the output array.
Accessing Structured Array Fields
We can access specific fields (columns) in the structured array by their names.
Pythonimportnumpyasnp# Define a list of recordsrecords=[(1,'Alice',25.5),(2,'Bob',30.0),(3,'Charlie',28.0)]# Define the data typedtype=[('id','i4'),('name','U10'),('age','f4')]# Create the structured arraystructured_array=np.fromrecords(records,dtype=dtype)# Access the 'name' fieldprint(structured_array['name'])# Access the 'age' fieldprint(structured_array['age'])
Output:
[(1, 'Alice', 25.5) (2, 'Bob', 30. ) (3, 'Charlie', 28. )]