python - 如果我有重复的日期,如何用 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 天的这些条件下进行计算?如果是这样,怎么做?
解决方案
另一个解决方案中的逻辑仍然是正确的;问题是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
推荐阅读
- hybris - 如何在 SAP Commerce Cloud/Hybris Backoffice 中显示“加载”-微调器动画?
- google-apps-script - 忽略 Google 应用脚本功能中的空单元格
- python - 使用 WHERE 和“'”查询时在 jupyter notebook 中查询错误
- go - grpc-gateway 服务没有响应 grpcurl 或 curl
- concurrency - JMETER 甚至为单线程运行创建多个进程线程
- c# - Firebase 云消息传递 .Net 服务器代码调试
- wordpress - 如何在 wordpress 中重写 URL?
- python-3.x - 带有 ssl 的 Python 套接字以防止中间攻击
- java - 接受带星号的正确字母。但是一个正确的字母+另一个字母,也接受
- javascript - 如何使用 THREE.js 在网页上加载动画 3D 模型