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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With