How to convert list of model objects to pandas dataframe?

Learn, how to convert list of model objects to pandas dataframe in Python? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose, we are given an array of objects, and we need to convert this into a dataframe for the purpose of using aggregate methods like sum, min, max, avg, etc.

Converting list of model objects to pandas dataframe

For this purpose, we will define a function inside a class so that we can use dataframe.from_records() method to create a dataframe with this array of objects.

Let us understand with the help of an example,

Python program to convert list of model objects to pandas dataframe

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a class
class c(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

# Defining a function
    def fun(self):
        return {
            'A': self.x,
            'B': self.y,
        }

# Creating array of objects
arr = [c(1, 2), c(3, 4)]

# Creating a dataframe from dictionary
df = pd.DataFrame.from_records([x.fun() for x in arr])

# Display DataFrame
print("DataFrame:\n",df)

Output

The output of the above program is:

Example: How to convert list of model objects to pandas dataframe?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.