python - How can I use `pivot` to track wins and loses? -
suppose have team data dataframe df.
home_team home_score away_team away_score 3 c 1 b 1 0 c 3 b 2 i'd dataframe indicating how many times 1 team has beat another. instance entry in [1,3] number of times team 1 has beat team 3, number in [3,1] number of times team 3 beat team 1.
this sounds df.pivot should able do, can't seem like.
how can accomplish using pandas?
here desired output
b c 0 0 1 b 1 0 0 c 0 1 0
this create new dataframe winners , loosers. can pivoted created looking for.
i made additional data fill in of pivot table values
import pandas pd data = {'home_team':['a','b','c','a','b','c','a','b','c'], 'home_score':[3,1,3,0,1,2,0,4,0], 'away_team':['c','a','b','b','c','b','c','a','a'], 'away_score':[1,0,2,2,0,3,1,7,1]} df = pd.dataframe(d) # create new dataframe wl = pd.dataframe() wl['winner'] = pd.concat([df.home_team[df.home_score>df.away_score], df.away_team[df.home_score<df.away_score]], axis=0) wl['loser'] = pd.concat([df.home_team[df.home_score<df.away_score], df.away_team[df.home_score>df.away_score]], axis=0) wl['game'] = 1 # groupby count number of win/lose pairs wl_gb = wl.groupby(['winner','loser']).count().reset_index() # pivot data wl_piv = wl_gb.pivot(index='winner', columns='loser', values='game') 
Comments
Post a Comment