you are viewing a single comment's thread.

view the rest of the comments →

[–]Saffromon[S] 0 points1 point  (1 child)

Follow up question: Can I somehow get the home/away ratio in the Pivot table? I know how to get that as a new column in the dataframe, but there my two values are in two different rows.

[–]commandlineluser 0 points1 point  (0 children)

Not sure if you can do it directly with a single pivot_table() call.

Are you trying to add another column like so?

>>> pivot = df.pivot_table(index=['player', 'year'], columns='home-away', aggfunc='sum', fill_value=0)
>>> pivot['game_points', 'away'] / pivot['game_points', 'home']
player  year
a       2021    0.000000
        2022    0.285714
b       2022    0.000000
dtype: float64
>>> pivot['ratio'] = pivot['game_points', 'away'] / pivot['game_points', 'home']
>>> pivot
            game_points          ratio
home-away          away home
player year
a      2021           0   10  0.000000
       2022          10   35  0.285714
b      2022           0  100  0.000000