Search code examples
pythonpandasgroup-byapply

Including the group name in the apply function


Is there away to specify to the groupby() call to use the group name in the apply() lambda function?

Similar to if I iterate through groups I can get the group key via the following tuple decomposition:

for group_name, subdf in temp_dataframe.groupby(level=0, axis=0):
    print group_name

...is there a way to also get the group name in the apply function, such as:

temp_dataframe.groupby(level=0,axis=0).apply(lambda group_name, subdf: foo(group_name, subdf)

How can I get the group name as an argument for the apply lambda function?


Solution

  • I think you should be able to use the nameattribute:

    temp_dataframe.groupby(level=0,axis=0).apply(lambda x: foo(x.name, x))
    

    should work, example:

    In [132]:
    df = pd.DataFrame({'a':list('aabccc'), 'b':np.arange(6)})
    df
    
    Out[132]:
       a  b
    0  a  0
    1  a  1
    2  b  2
    3  c  3
    4  c  4
    5  c  5
    
    In [134]:
    df.groupby('a').apply(lambda x: print('name:', x.name, '\nsubdf:',x))
    
    name: a 
    subdf:    a  b
    0  a  0
    1  a  1
    name: b 
    subdf:    a  b
    2  b  2
    name: c 
    subdf:    a  b
    3  c  3
    4  c  4
    5  c  5
    Out[134]:
    Empty DataFrame
    Columns: []
    Index: []