1 回答
TA贡献1842条经验 获得超21个赞
我相信需要rename_axis
使用add
和DataFrame
使用相同名称的 MultiIndex reset_index
:
leaguesFinal = pd.DataFrame({
'Home Team': ['b','a','a','c','b','a'],
'Away Team': ['a','b','c','a','a','b'],
'season': ['2010/2011'] * 3 + ['2012/2013'] * 3,
'home_team_goal': [1,2,3,4,3,2],
'away_team_goal': [4,6,7,8,2,1]
})
print (leaguesFinal)
Home Team Away Team season home_team_goal away_team_goal
0 b a 2010/2011 1 4
1 a b 2010/2011 2 6
2 a c 2010/2011 3 7
3 c a 2012/2013 4 8
4 b a 2012/2013 3 2
5 a b 2012/2013 2 1
home_goals = leaguesFinal.groupby(['Home Team', 'season'])['home_team_goal'].sum()
away_goals = leaguesFinal.groupby(['Away Team', 'season'])['away_team_goal'].sum()
print (home_goals)
Home Team season
a 2010/2011 5
2012/2013 2
b 2010/2011 1
2012/2013 3
c 2012/2013 4
Name: home_team_goal, dtype: int64
print (away_goals)
Away Team season
a 2010/2011 4
2012/2013 10
b 2010/2011 6
2012/2013 1
c 2010/2011 7
Name: away_team_goal, dtype: int64
a = home_goals.rename_axis(['Team','season'])
b = away_goals.rename_axis(['Team','season'])
df = (a.add(b, fill_value=0)).reset_index(name='both')
print (df)
Team season both
0 a 2010/2011 9.0
1 a 2012/2013 12.0
2 b 2010/2011 7.0
3 b 2012/2013 4.0
4 c 2010/2011 7.0
5 c 2012/2013 4.0
添加回答
举报