dejsdukes
dejsdukes

Reputation: 121

pandas - Select Last Row of Column Based on Different Column Value

I've got a dataframe like

    Season   Game   Event_Num        Home         Away         Margin
0   2016-17     1          1           0           0             0
1   2016-17     1          2           0           0             0
2   2016-17     1          3           0           2             2
3   2016-17     1          4           0           2             2
4   2016-17     1          5           0           2             2
..      ...   ...        ...         ...         ...           ...
95  2017-18     5         53          17          10             7
96  2017-18     5         54          17          10             7
97  2017-18     5         55          17          10             7
98  2017-18     5         56          17          10             7
99  2017-18     5         57          17          10             7

And ultimately, I'd like to take the last row of each Game played, so for instance, the last row for Game 1, Game 2, etc. so I can see what the final margin was, but I'd like to do this for every unique season.

For example, if there were 3 games played for 2 unique seasons then the df would look something like:

        Season   Game   Event_Num        Home         Away        Final Margin
    0   2016-17     1          1          90           80            10
    1   2016-17     2          2          83           88             5
    2   2016-17     3          3          67           78            11
    3   2017-18     1          4         101          102             1
    4   2017-18     2          5         112          132            20
    5   2017-18     3          6          

Is there a good way to do something like this? TIA.

Upvotes: 2

Views: 578

Answers (1)

Mutaz-MSFT
Mutaz-MSFT

Reputation: 806

Try:

df.groupby(['Season','Game']).tail(1)

output

    Season  Game  Event_Num  Home  Away  Margin
4  2016-17     1          5     0     2       2
9  2017-18     5         57    17    10       7

Upvotes: 2

Related Questions