I have the following Dataframe:
| Track | FGrating | HorseId | Last FGrating at Happy Valley Grass |
|---|---|---|---|
| Happy Valley grass | 97 | 22609 | |
| Happy Valley grass | 106 | 22609 | 97 |
| Happy Valley grass | 104 | 22609 | 106 |
| Happy Valley grass | 102 | 22609 | 104 |
| Happy Valley grass | 95 | 22609 | 102 |
| Sha Tin grass | 108 | 22609 | |
| Sha Tin grass | 104 | 22609 | |
| Happy Valley grass | 107 | 22609 | 95 |
| Sha Tin grass | 102 | 22609 | |
| Happy Valley grass | 108 | 22609 | 107 |
I need to fill the empty cells of the rightmost column according to these two rules:
- If the horse didn't race on the particular track yet (Happy Valley grass, in this example), then the value to be filled is 0;
- Between two races at the particular track (Happy Valley grass, in this example), the value to be filled is the last FGrating on the track in question (the two consecutive rows with Sha Tin grass will get the value 95 and the third one will get 107).
The end result will be like this:
| Track | FGrating | HorseId | Last FGrating at Happy Valley Grass |
|---|---|---|---|
| Happy Valley grass | 97 | 22609 | 0 (rule 1) |
| Happy Valley grass | 106 | 22609 | 97 |
| Happy Valley grass | 104 | 22609 | 106 |
| Happy Valley grass | 102 | 22609 | 104 |
| Happy Valley grass | 95 | 22609 | 102 |
| Sha Tin grass | 108 | 22609 | 95 (rule 2) |
| Sha Tin grass | 104 | 22609 | 95 (rule 2) |
| Happy Valley grass | 107 | 22609 | 95 |
| Sha Tin grass | 102 | 22609 | 107 (rule 2) |
| Happy Valley grass | 108 | 22609 | 107 |
I need this for every HorseId on the Dataframe
I tried doing a backfill then filling with 0, something like this:
df['Last FGrating at Happy Valley Grass'] = df.groupby('HorseId')['Last FGrating at Happy Valley Grass'].apply(
lambda x: x.fillna(method='bfill').fillna(0))
but it backfills everything, ignoring rule 1.
Can you help me here? Doing some research here, I have the feeling that it is a bit more complicated than a string of fillna.