Open In App

Python - Numpy fromrecords() method

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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): If True, 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. )]

Next Article
Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy