Pandas DataFrame From_records Method

Beginner

Introduction

The DataFrame.from_records() method in Pandas is used to convert structured or record ndarray to a DataFrame. It can create a DataFrame object from a structured ndarray, sequence of tuples, or DataFrame.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import the necessary libraries

First, import the pandas and numpy libraries to use the functions and methods later in the code.

import pandas as pd
import numpy as np

Create a structured ndarray

Next, create a structured ndarray, which contains structured input data. This ndarray can be created by using the numpy.array function and specifying the data type for each field. For example:

data = np.array([(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')], dtype=[('col_1', 'i4'), ('col_2', 'U1')])

Convert ndarray to DataFrame

Use the DataFrame.from_records() method to convert the structured ndarray into a DataFrame. This method takes the structured ndarray as the input data and returns a DataFrame object. Assign the DataFrame object to a variable to be able to access and manipulate the DataFrame later. For example:

df = pd.DataFrame.from_records(data)

Display the DataFrame

Print the DataFrame to see the results. Using the print() function will display the DataFrame in a tabular format. For example:

print(df)

Summary

By following these steps, you can use the DataFrame.from_records() method in Pandas to convert a structured ndarray into a DataFrame. This method is useful when working with structured input data and allows for easy manipulation and analysis of the data using the powerful features of Pandas.