13

Suppose I have a DataFrame including following columns "NAME", "SURNAME", "AGE" and I would like to create one object for each row, including those column values as its variables.

person = ConvertRow2Object(frame.iloc[0,:])
print person.NAME //outputs Gary

How can I do it with a generic solution to any DataFrame with any kind of column names and data types?

1
  • Does it have to be an object accessible via dot notation or can it be a dictionary accessible by a key (e.g. person['name'])? Commented Aug 12, 2014 at 21:26

2 Answers 2

15

You can convert the whole thing to a numpy recarray, then each record in the array is attributed:

people = frame.to_records()
person = people[0]
print person.NAME  # etc...

Using a namedtuple also seems to work:

from collections import namedtuple

Person = namedtuple('Person', frame.dtypes.index.tolist())
person = Person(*frame.iloc[0,:])
print person.NAME  # etc...
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean with // ...? Is that suposed to be a C style comment?
Wow, blast from the past. No, I think I just meant a break from any other things you'd want to print. I should just use ....
2

This technique of creating dictionary objects and passing that as init argument worked for me. This is also more generic in that you don't need to type in the key / property names

# AppInfo = Class which I wanted to create instance objects for each row in df 
class AppInfo:
    def __init__(self, attr_dict):
        if attr_dict is not None:
            for key, value in attr_dict.items():
                setattr(self, key.replace(' ', '_'), value)


# in my code this methods creates a list of AppInfo objects created from the dataframe

def get_app_infos() -> List[AppInfo]:
    df = data.query_from_db()
    [AppInfo(a) for a in df.to_dict('records')]

Comments

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.