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:

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. )]

Similar Reads

Introduction







Creating NumPy Array













NumPy Array Manipulation


















Matrix in NumPy


















Operations on NumPy Array




Reshaping NumPy Array















Indexing NumPy Array






Arithmetic operations on NumPyArray










Linear Algebra in NumPy Array