简体   繁体   中英

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

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

This gives your expected output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM