Priyanka
Priyanka

Reputation: 43

python code for creating class object from dataframe rows

I have one data frame with row entries and column names. I also have a class defined with attributes (class attribute names are different from dataframe columns).

Now the requirement is to create objects of that class per record from the dataframe and the final list of objects should be output

Class A:

AA, AB, AC....etc

dataframe:

A B c ...
1 2 3 ...
1 2 3 ...

How to avoid column names and start creating objects?

I have tried using this code:

Aobjs = [A(**kwargs) for kwargs in dataframe.to_dict(orient='records')]

Upvotes: 4

Views: 10930

Answers (1)

Mike
Mike

Reputation: 858

Will something like this work for you?:

df = pd.DataFrame({'one': [1, 2, 3], 'two': [ 6, 5, 4]})
df
#    one  two
# 0    1    6
# 1    2    5
# 2    3    4

class Silly:
    def __init__(self, first, second):
        self.first = first
        self.second = second

A = [Silly(a.one, a.two) for a in df.itertuples()]
# [<__main__.Silly object at 0x7f97b26fe7f0>, <__main__.Silly object at 0x7f97b26fe978>, <__main__.Silly object at 0x7f97b26fe4a8>]

My guess is that your index is not a valid kwarg.

Upvotes: 6

Related Questions