close

How to convert list of model objects to pandas dataframe?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert list of model objects to pandas dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to convert list of model objects to pandas dataframe?

  1. How to convert list of model objects to pandas dataframe?

    A much cleaner way to to this is to define a to_dict method on your class and then use pandas.DataFrame.from_records

  2. convert list of model objects to pandas dataframe

    A much cleaner way to to this is to define a to_dict method on your class and then use pandas.DataFrame.from_records

Method 1

A much cleaner way to to this is to define a to_dict method on your class and then use pandas.DataFrame.from_records

class Signal(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def to_dict(self):
        return {
            'x': self.x,
            'y': self.y,
        }

e.g.

In [87]: signals = [Signal(3, 9), Signal(4, 16)]

In [88]: pandas.DataFrame.from_records([s.to_dict() for s in signals])
Out[88]:
   x   y
0  3   9
1  4  16

Method 2

Just use:

DataFrame([o.__dict__ for o in my_objs])

Full example:

import pandas as pd

# define some class
class SomeThing:
    def __init__(self, x, y):
        self.x, self.y = x, y

# make an array of the class objects
things = [SomeThing(1,2), SomeThing(3,4), SomeThing(4,5)]

# fill dataframe with one row per object, one attribute per column
df = pd.DataFrame([t.__dict__ for t in things ])

print(df)

This prints:

   x  y
0  1  2
1  3  4
2  4  5

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read