Groupby function in python pandas

From raju

number of calls when using apply on a groupby object

When using apply() on a groupby object, the underlying function is called n+1 times when there are n groups. This is explained in https://stackoverflow.com/questions/21390035/python-pandas-groupby-object-apply-method-duplicates-first-group

google searches | groupby number of calls to the apply function

Get three largest values from each group

Using group specific information inside the apply function

The trick is to use the .name attribute when the apply function is called. For example consider

    In [1]:
    df = pd.DataFrame({'a':list('aabccc'), 'b':np.arange(6)})
    print df
    
    Out[1]:
       a  b
    0  a  0
    1  a  1
    2  b  2
    3  c  3
    4  c  4
    5  c  5
    
    In [2]:
    def bar(df, id):
        print 'name:', id, '\nsubdf:\n', df
    df_grp = df.groupby('a')
    df_grp.apply(lambda x: bar(x, x.name))
    
    Out[2]:
    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
    

Ref:- https://stackoverflow.com/questions/32460593/including-the-group-name-in-the-apply-function-pandas-python

google searches | python pandas apply name attribute, python groupby ".name" attribute, python how to get the group name in agg function

demonstrates | apply a function that takes multiple arguments on a groupby object