如何将每个Pandas数据框行转换为包含列值作为属性的对象?

11 投票
2 回答
12664 浏览
提问于 2025-04-18 17:04

假设我有一个数据表,里面有“姓名”、“姓氏”和“年龄”这些列。我想为每一行创建一个对象,把这些列的值作为对象的属性。

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

我该怎么做,才能对任何数据表,不管列名和数据类型是什么,都能用一个通用的方法来实现呢?

2 个回答

2

这种创建字典对象并将其作为init参数传递的方法对我来说很有效。而且这个方法更通用,因为你不需要手动输入键或属性的名称。

 #AppInfo = Class which I wanted to create instance objects for each row in df 
    def 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('r')]
15

你可以把整个内容转换成一个numpy的记录数组,这样数组里的每一条记录都有自己的属性:

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

使用命名元组(namedtuple)也能达到这个效果:

from collections import namedtuple

Person = namedtuple('Person', frame.dtypes.index.tolist())
person = Person(*frame.iloc[0,:])
print person.NAME  # etc...

撰写回答