gpt4 book ai didi

python - Pandas 滚动时间总和

转载 作者:行者123 更新时间:2023-11-30 22:04:44 26 4
gpt4 key购买 nike

我正在尝试在数据框中获取时间值的滚动总和,如下所示:

    RunTime
0 00:51:25
1 NaT
2 00:42:16
3 NaT
4 00:40:15
5 NaT
6 00:50:13
7 00:53:28
8 NaT
9 00:37:32
10 NaT
11 01:53:22
12 01:08:22
13 00:59:57
14 00:12:22

预期输出:

     RunTime  RunTime_MS
0 00:51:25
1 NaT
2 00:42:16
3 NaT
4 00:40:15
5 NaT
6 00:50:13 3:04:09
7 00:53:28 3:06:12
8 NaT 3:06:12
9 00:37:32 3:01:28
10 NaT 3:01:28
11 01:53:22 4:14:35
12 01:08:22 5:22:57
13 00:59:57 5:32:41
14 00:12:22 4:51:35

对于我正在使用的数据框中的其他列(包含 float )

dfExt['Distance_MS'] = dfExt['Distance'].fillna(value=0).rolling(window=7).sum()

运行得很好。如果我尝试在时间列上执行此操作,则会收到错误

ops for Rolling for this dtype timedelta64[ns] are not implemented

尽管the documentation似乎表明 .sum() 是您可以在 timedelta 上执行的操作。

这是示例代码:

import pandas as pd
from datetime import datetime, timedelta

RunTimeValues = ['00:51:25','','00:42:16','','00:40:15','','00:50:13','00:53:28','','00:37:32','','01:53:22','01:08:22','00:59:57','00:12:22']
for i in range(len(RunTimeValues)):
if RunTimeValues[i] != '':
#RunTimeValues[i] = datetime.strptime(RunTimeValues[i], "%H:%M:%S")
t = datetime.strptime(RunTimeValues[i],"%H:%M:%S")
RunTimeValues[i] = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
dfExt = pd.DataFrame({'RunTime': RunTimeValues})
dfExt['RunTime_MS'] = dfExt['RunTime'].fillna(value=0).rolling(window=7).sum()
print(dfExt)

我知道我可以将时间增量转换为浮点形式的小时,然后进行滚动求和,但该结果并不完全是我想要的。有什么建议么?

最佳答案

这样就可以了:

dfExt['RunTime_MS'] = pd.to_timedelta(dfExt['RunTime'].fillna(0).dt.total_seconds().rolling(window=7).sum(), unit='s')
print(dfExt)
RunTime RunTime_MS
0 00:51:25 NaT
1 NaT NaT
2 00:42:16 NaT
3 NaT NaT
4 00:40:15 NaT
5 NaT NaT
6 00:50:13 03:04:09
7 00:53:28 03:06:12
8 NaT 03:06:12
9 00:37:32 03:01:28
10 NaT 03:01:28
11 01:53:22 04:14:35
12 01:08:22 05:22:57
13 00:59:57 05:32:41
14 00:12:22 04:51:35

关于python - Pandas 滚动时间总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com