有没有一种方法可以通过将两个其他列按相同的值分组来对2列求和?

时间:2020-07-07 19:47:08

标签: python pandas

我正在使用这样的数据框:

home_team away_team  home_score  away_score 
Scotland   England           0           0   
England   Scotland           4           2   
Scotland   England           2           1   
England   Scotland           2           2   
Scotland   England           3           0   

这是我想完成的任务,我正在尝试将整个国家/地区重新组合在一起,无论他们是在家还是外出,并获得总分。

Team    total goal
Scotland   9
England    7

2 个答案:

答案 0 :(得分:4)

尝试一下,如果您遇到任何问题/错误,请告诉我。在这里,您去了:

df.groupby("home_team").home_score.sum()+df.groupby("away_team").away_score.sum()

答案 1 :(得分:0)

这应该可以解决问题(假设您原来的DataFrame称为df):

nations = ["England", "Scotland"]
tot = pd.DataFrame([(nation, 0) for nation in nations], columns=["team","total goal"])

for nation in nations:
    home_goal = sum(df[df["home_team"] == nation]["home_score"])
    away_goal = sum(df[df["away_team"] == nation]["away_score"]) 
    tot.loc[tot.team == nation, "total goal"] = home_goal + away_goal