Instantiate a class in a groupby method

后端 未结 1 1159
不知归路
不知归路 2021-01-23 10:38

I have the following class for a file:

class File:
    def __init__(self, file_name, md5):
        self.file_name = file_name
        self.md5 = md5
    def do_so         


        
相关标签:
1条回答
  • 2021-01-23 11:10

    I'm not sure, if this is a solution. You can instantiate objects in the apply method. I created an example class and dataframe.

    class Test:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
    df = pd.DataFrame({
        'group': list('abbaabcc'),
        'group2': list('abababab'),
        'a': [1,2,1,2,3,2,3,4],
        'b': [3,4,2,3,4,5,3,4]
    })
    df
    

    Output

      group group2  a  b
    0     a      a  1  3
    1     b      b  2  4
    2     b      a  1  2
    3     a      b  2  3
    4     a      a  3  4
    5     b      b  2  5
    6     c      a  3  3
    7     c      b  4  4
    

    Create Objects in apply

    df.groupby(['group','group2'])[['a','b']].apply(
        lambda x: [Test(e[0],e[1]) for _,e in x.iterrows()])
    

    Output

    group  group2
    a      a         [<__main__.Test object at 0x7f5351df0390>, <__...
           b                [<__main__.Test object at 0x7f5351df03d0>]
    b      a                [<__main__.Test object at 0x7f5351df0450>]
           b         [<__main__.Test object at 0x7f5351df0490>, <__...
    c      a                [<__main__.Test object at 0x7f5351df0550>]
           b                [<__main__.Test object at 0x7f5351df04d0>]
    dtype: object
    
    0 讨论(0)
提交回复
热议问题