Home > Net >  How to Get Sum of column value, after groupby another column in Pandas?
How to Get Sum of column value, after groupby another column in Pandas?

Time:01-12

I have a Pandas data frame, as shown below, with multiple columns and would like to get the total of column, 'Score' after grouby 'Region','Team'.

input: input

Code:

import pandas as pd

df=pd.read_csv(txtfile, sep='\t')
df=df.groupby(['Region','Team']).Score.count().to_frame('New_Score').reset_index()
df.to_csv('Counts.txt',sep='\t',index=False)

Expected_output: output

CodePudding user response:

This gives your expected output :

df2 = df.groupby(['Team','Region']).sum()
df2.rename(columns = {'Score' : 'New Score'}, inplace = True)
df2.reset_index()
  •  Tags:  
  • Related