How can I fill a column with values that are computed between two dates in pandas, if I have repeating dates?

Viewed 353

This question is a variation of this one, the only difference being that the dates can repeat in the rows of a DataFrame. So, the example would be:

Date Position TrainerID Win%
2017-09-03 4 1788 0 (0 wins, 1 race)
2017-09-16 5 1788 0 (0 wins, 2 races)
2017-10-14 1 1788 33 (1 win, 3 races)
2017-10-14 3 1788 25 (1 win, 4 races)

Is it possible to compute Win% in these conditions for the last 1000 days? If so, how?

1 Answers

The logic in the other solution is still correct; the issue is that groupby + rolling destroys the Index so it becomes problematic to align the result back to the original DataFrame.

In this case, you can .reset_index and use max (assuming a RangeIndex) to bring along the original Index. This allows you to aggregate, then align the result back.

I added an additional row at the end to show you how it enforces the 1000 day window.

# If your DataFrame doesn't have a RangeIndex this is required for the logic
#df = df.reset_index(drop=True)

df['win'] = df['Position'].eq(1) 

s = (df.reset_index().groupby('TrainerID')
       .rolling('1000D', on='Date')
       .agg({'win': 'mean', 'index': 'max'})
       .reset_index(drop=True)
       .set_index('index')
       .mul(100))  
#              win
#index            
#0.0      0.000000
#1.0      0.000000
#2.0     33.333333
#3.0     25.000000
#4.0    100.000000

df['Win %'] = s

print(df)
        Date  Position  TrainerID    win       Win %
0 2017-09-03         4       1788  False    0.000000
1 2017-09-16         5       1788  False    0.000000
2 2017-10-14         1       1788   True   33.333333
3 2017-10-14         3       1788  False   25.000000
4 2027-10-14         1       1788   True  100.000000
Related