How to convert list of model objects to pandas dataframe?

后端 未结 5 1961
遥遥无期
遥遥无期 2020-12-23 13:30

I have an array of objects of this class

class CancerDataEntity(Model):

    age = columns.Text(primary_key=True)
    gender = columns.Text(primary_key=True)         


        
5条回答
  •  被撕碎了的回忆
    2020-12-23 14:01

    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
    

提交回复
热议问题