With the pandas dataframe below (which is a set of results, per team, ordered chronologically)
Team | Result |
---|---|
TeamA | Win |
TeamA | Loss |
TeamA | Win |
TeamB | Loss |
TeamB | Loss |
TeamC | Loss |
TeamC | Win |
TeamC | Win |
TeamC | Loss |
TeamC | Loss |
I want to iterate through the dataset and add a new column ("GameNumber") which denotes whether a game is the 1st, 2nd etc. game of each team's season.
i.e. the GameNumber value continues to increment until it find a row where the "Team" value differs from the row above. When it finds such a row, it resets the counter and begins counting from '1' again.
- Sample desired result
Team | Result | GameNumber |
---|---|---|
TeamA | Win | 1 |
TeamA | Loss | 2 |
TeamA | Win | 3 |
TeamB | Loss | 1 |
TeamB | Loss | 2 |
TeamC | Loss | 1 |
TeamC | Win | 2 |
TeamC | Win | 3 |
TeamC | Loss | 4 |
TeamC | Loss | 5 |
Many thanks!
I've tried various pandas functions (incl. explode & groupby) but these don't seem to meet the need.