Skip to content Skip to sidebar Skip to footer

Create New Dataframe For Each Tennis Player

I have a dataframe for tennis players results : match match_date score result player_name 0 match1 06June 6-2 winner player1 2 match3 07June 5-6 wi

Solution 1:

You could use this:

result = df.set_index(['player_name','match']).unstack()
print(result.to_string())
            match_date                          score                       result                       
match           match1  match2  match3  match4 match1 match2 match3 match4  match1  match2  match3 match4
player_name                                                                                              
player1         06June  08June  07June     NaN6-26-45-6NaN  winner   loser  winner    NaN
player2         06June     NaNNaNNaN6-2NaNNaNNaN   loser     NaNNaNNaN
player3            NaN08June     NaN12June    NaN6-4NaN6-7NaN  winner     NaN  loser

If you want the exact output as you expect, you might have to change the match column so it starts at match 0 for each player like this:

df['match'] ='match'+ df.groupby('player_name')['match'].cumcount().astype(str)

result= df.set_index(['player_name', 'match']).unstack()
print(result.to_string())
            match_date                  score                resultmatch           match0  match1  match2 match0 match1 match2  match0  match1 match2
player_name                                                                       
player1         06June  07June  08June    6-25-66-4  winner  winner  loser
player2         06June     NaN     NaN    6-2    NaN    NaN   loser     NaN    NaN
player3         08June  12June     NaN    6-46-7    NaN  winner   loser    NaN

Post a Comment for "Create New Dataframe For Each Tennis Player"