首页 > 解决方案 > 如果我有重复的日期,如何用 pandas 中两个日期之间计算的值填充一列?

问题描述

这个问题是这个问题的一个变体唯一的区别是日期可以在 DataFrame 的行中重复。因此,示例将是:

日期 位置 培训师ID 赢%
2017-09-03 4 1788 0(0胜,1场比赛)
2017-09-16 5 1788 0(0胜,2场比赛)
2017-10-14 1 1788 33(1胜,3场比赛)
2017-10-14 3 1788 25(1 胜,4 场比赛)

是否可以Win%在过去 1000 天的这些条件下进行计算?如果是这样,怎么做?

标签: pythonpandas

解决方案


另一个解决方案中的逻辑仍然是正确的;问题是groupby+rolling破坏了索引,因此将结果与原始 DataFrame 对齐变得有问题。

在这种情况下,您可以.reset_index使用max(假设是 RangeIndex)来带来原始索引。这允许您聚合,然后将结果对齐。

我在最后添加了一行,向您展示它如何强制执行 1000 天窗口。

# 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

推荐阅读