Show group on every record in groupby

Viewed 975

I am using pandas and groupby to aggregate. I'm doing the following:

data = {'ac' : ['a','a','a','a','a','a','a','a','b','b','b','b','b'],
        'cls'   ['wwww','wwww','wwww','xxxx','xxxx','zzzz','zzzz','yyyy','wwww','xxxx','zzzz','zzzz','yyyy'],
        'pl' : [1,1,1,1,1,1,1,1,1,1,1,1,1]}

df = pd.DataFrame(data)

grouped = df.groupby(['ac','cls']).agg({'pl':np.sum})


           pl
    ac cls     
    a  wwww   3
       xxxx   2
       yyyy   1
       zzzz   2
    b  wwww   1
       xxxx   1
       yyyy   1
       zzzz   2

Is there a way to do the groupby where it will fill in the ac column so that it reads like the following?

             pl
    ac cls     
    a  wwww   3
    a  xxxx   2
    a  yyyy   1
    a  zzzz   2
    b  wwww   1
    b  xxxx   1
    b  yyyy   1
    b  zzzz   2
3 Answers

Use as_index=True

In [748]: df.groupby(['ac', 'cls'], as_index=False).agg({'pl': np.sum})
Out[748]:
  ac   cls  pl
0  a  wwww   3
1  a  xxxx   2
2  a  yyyy   1
3  a  zzzz   2
4  b  wwww   1
5  b  xxxx   1
6  b  yyyy   1
7  b  zzzz   2
Related