首页 > 解决方案 > 用数据框中的属性值替换类对象

问题描述

我有一个包含不同数据类型的数据框,例如这里有两个类 FirstGroup 和 LastGroup。

    id1                     id2                     id3...                               
0   (0, FirstGroup.Other)   (0, FirstGroup.Other)   (0, FirstGroup.Static)  ...    
1  (60, LastGroups.Other)  (22, LastGroups.Other)  (49, LastGroups.Static)  ... 

所有这些对象都存储了我想以有效方式提取的数据。一个例子是:df['id1'].[0][1].name会给我一个字符串变量'type1'

我想要这样的东西:

    id1            id2            id3...                               
0   (0, 'type1')   (0, 'type1')   (0, 'type2')  ...    
1  (60, 'type1')  (22, 'type1')  (49, 'type2')  ... 

我正在寻找与替换方法类似的东西,但除了遍历每一行和每一列外,什么都做不了。

标签: python-3.xpandasdataframenumpy

解决方案


您可以使用applymap

df.applymap(lambda x: (x[0], x[1].name))

完整示例:

class O:
    def __init__(self):
        self.name = str(id(self))[-5:]
    def __repr__(self):
        return 'CustomObject'

df = pd.DataFrame({'id%s' % i: [(j, O()) for j in range(2)] for i in range(3)})
df.applymap(lambda x: (x[0], x[1].name))

输入:

                 id0                id1                id2
0  (0, CustomObject)  (0, CustomObject)  (0, CustomObject)
1  (1, CustomObject)  (1, CustomObject)  (1, CustomObject)

输出:

          id0         id1         id2
0  (0, 95984)  (0, 98096)  (0, 97712)
1  (1, 97328)  (1, 98720)  (1, 97280)

推荐阅读