Python Numpy fromrecords() method (original) (raw)
Last Updated : 28 Jan, 2025
**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:
Python `
import numpy as np
Define a list of records
records = [(1, 'Alice', 25.5), (2, 'Bob', 30.0), (3, 'Charlie', 28.0)]
Define the data type
dtype = [('id', 'i4'), ('name', 'U10'), ('age', 'f4')]
Create the structured array
structured_array = np.fromrecords(records, dtype=dtype)
print(structured_array)
`
**Output:
[(1, 'Alice', 25.5) (2, 'Bob', 30. ) (3, 'Charlie', 28. )]
Table of Content
Syntax of Numpy fromrecords():
numpy.fromrecords(recList, dtype=None, shape=None, aligned=False, byteorder=None)
**Parameters:
recList
: A list of tuples or structured data to be converted into a structured NumPy 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.
Python `
import numpy as np
Define a list of records
records = [(1, 'Alice', 25.5), (2, 'Bob', 30.0), (3, 'Charlie', 28.0)]
Define the data type
dtype = [('id', 'i4'), ('name', 'U10'), ('age', 'f4')]
Create the structured array
structured_array = np.fromrecords(records, dtype=dtype)
Access the 'name' field
print(structured_array['name'])
Access the 'age' field
print(structured_array['age'])
`
**Output:
[(1, 'Alice', 25.5) (2, 'Bob', 30. ) (3, 'Charlie', 28. )]