我提出了自己的解决方案:
# Split into quarters
new = pd.DataFrame(((
e.name,
e.flag,
# for the first interval use the starttime
e.starttime if date == e.starttime.floor('15min') else date,
# for the last interval use the endtime
e.endtime if date == e.endtime.floor('15min') else date + pd.Timedelta(minutes=15)
)
#iterate over thet uples
for e in df.itertuples()
# iterate for each range date
for date in pd.date_range(e.starttime.floor('15min'), e.endtime.floor('15min'), freq='15min')
), columns = ['name', 'flag', 'start', 'end'])
# calculate the duration
new['duration'] = new['end']- new['start']
然而,它并不完全优雅,我需要修复沿途可能导致错误的许多细节。这似乎是一个非常典型的用例,所以我相信应该有更好的解决方案。
最终结果
我的最终数据集看起来像这样。我可以重用一些列,但我认为这种方式很清楚地反映了为实现这个解决方案所采取的步骤数量。
name flag start end duration
0 Alice y 2020-03-20 15:05:00 2020-03-20 15:15:00 00:10:00
1 Alice y 2020-03-20 15:15:00 2020-03-20 15:30:00 00:15:00
2 Alice y 2020-03-20 15:30:00 2020-03-20 15:41:00 00:11:00
3 Bob m 2020-03-20 15:16:00 2020-03-20 15:30:00 00:14:00
4 Bob m 2020-03-20 15:30:00 2020-03-20 15:40:00 00:10:00
5 Chap y 2019-03-20 12:58:00 2019-03-20 13:00:00 00:02:00
6 Chap y 2019-03-20 13:00:00 2019-03-20 13:15:00 00:15:00
7 Chap y 2019-03-20 13:15:00 2019-03-20 13:30:00 00:15:00
8 Chap y 2019-03-20 13:30:00 2019-03-20 13:41:00 00:11:00
9 Dana y 2020-03-20 20:05:00 2020-03-20 20:15:00 00:10:00
10 Dana y 2020-03-20 20:15:00 2020-03-20 20:30:00 00:15:00
11 Dana y 2020-03-20 20:30:00 2020-03-20 20:44:00 00:14:00