4

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')]
1
  • 1
    Can you post actual code for generating a simplified sample dataframe, please? (df1 = pd.DataFrame(...)) Also, it would be more helpful for you to show us an actual DataFrame with the desired result from the simplified sample. (result = pd.DataFrame...) Otherwise, it will be very difficult to help you. Minimal, Reproducible Example Commented May 29, 2019 at 1:36

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I am planning on writing a similar Class whose attributes are values of a dataframe column. Attribute names are the column names. Seeing that you name you class Silly is making twice. Can you explain why you name your class Silly?:)
@BND, I believe he was simply using a name like Foo and trying to reflect the simplicity of the example.
this more generic approach worked for me stackoverflow.com/a/75420677/98232

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.