【问题标题】:Replace class objects with attribute values in dataframe用数据框中的属性值替换类对象
【发布时间】:2021-08-25 10:36:02
【问题描述】:

我有一个数据框,其中包含不同的数据类型,例如有两个类 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.x pandas dataframe numpy


    【解决方案1】:

    你可以使用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)
    

    【讨论】:

    • 谢谢,正是我需要的!
    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 2013-08-23
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多