How To Calculate Sum|mean|median For Tail Of Each Group When Pandas Data Aggregated In Python
i am having data like following.which is in pandas data frame format. A B C D E F G 1 1 2 3 1 4 2 1 1 2 4 5 6 7 1 1 2 3 2 3 2 1 1 2 4 5 6 7 2 1 2 3
Solution 1:
Use GroupBy.transform
instead agg
for return new column with same shape as filtered DataFrame by tail
:
agg_lvl=['A','B','C']
df = df.groupby(agg_lvl,as_index=False).tail(2)
df['G'] = df.groupby(agg_lvl)['G'].transform('mean')
print (df)
A B C D E F G
2 1 1 2 3 2 3 4.5
3 1 1 2 4 5 6 4.5
5 2 1 2 3 4 3 5.0
6 2 1 2 4 5 6 5.0
EDIT:
df = df.groupby(agg_lvl,as_index=False).tail(2).groupby(agg_lvl,as_index=False)['G'].mean()
print (df)
A B C G
0 1 1 2 4.5
1 2 1 2 5.0
Post a Comment for "How To Calculate Sum|mean|median For Tail Of Each Group When Pandas Data Aggregated In Python"