这是一个数据框示例:
days = ['2019-07-04 17:02:03', '2019-07-04 17:03:03',
'2019-07-04 18:04:03', '2019-07-04 19:05:03',
'2019-07-04 21:06:03', '2019-07-04 21:36:03',
'2019-07-04 21:50:03', '2019-07-04 22:10:03']
ddf = pd.DataFrame({'Val': [0, 1, 2, 1, 4,1,3,1],'Cat':["A","A","A","A","B","B","B","B"]},
index= days)
ddf.index = pd.to_datetime(ddf.index)
Val Cat
2019-07-04 17:02:03 0 A
2019-07-04 17:03:03 1 A
2019-07-04 18:04:03 2 A
2019-07-04 19:05:03 1 A
2019-07-04 21:06:03 4 B
2019-07-04 21:36:03 1 B
2019-07-04 21:50:03 3 B
2019-07-04 22:10:03 1 B
如果我将滚动总和应用于1小时窗口,则会得到以下信息:
ddf.groupby("Cat")["Val"].rolling("1h").sum().rename('sum_last_hour')
Cat
A 2019-07-04 17:02:03 0.0
2019-07-04 17:03:03 1.0
2019-07-04 18:04:03 2.0
2019-07-04 19:05:03 1.0
B 2019-07-04 21:06:03 4.0
2019-07-04 21:36:03 5.0
2019-07-04 21:50:03 8.0
2019-07-04 22:10:03 5.0
Name: sum_last_hour, dtype: float64
Name: sum_last_hour, dtype: float64
但是我想得到这个:
Cat
A 2019-07-04 17:02:03 NaN
2019-07-04 17:03:03 0.0
2019-07-04 18:04:03 NaN
2019-07-04 19:05:03 NaN
B 2019-07-04 21:06:03 NaN
2019-07-04 21:36:03 4.0
2019-07-04 21:50:03 5.0
2019-07-04 22:10:03 4.0
Name: sum_last_hour, dtype: float64
所以我基本上想从滚动总和中排除当前行,如果这有意义的话... 我尝试使用shift(),但目前没有成功。 感谢您的帮助!
答案 0 :(得分:0)
实际上我只是发现了它。您需要在closed
函数中使用rolling()
参数,并将其设置为left
。这样的事情给了我很好的结果:
ddf.groupby("Cat").rolling("1h", closed= "left")["Val"].sum().rename('sum_last_hour')