Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show group on every record in groupby

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
like image 260
Binoy Fernandez Avatar asked Jun 02 '17 16:06

Binoy Fernandez


1 Answers

You want to reset the index:

import pandas as pd

import numpy as np

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})
grouped.reset_index(inplace=True)

print grouped

This prints:

  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
like image 199
asongtoruin Avatar answered Sep 28 '22 06:09

asongtoruin