gpt4 book ai didi

python - Pandas duration groupby - 以定义的值开始组范围

转载 作者:行者123 更新时间:2023-11-28 18:01:12 24 4
gpt4 key购买 nike

我正在尝试以 5 分钟的间隔对旅行持续时间的数据集进行分组,从 0 到 inf。我该怎么做?

我的示例数据框如下所示:

    Duration
0 00:01:37
1 00:18:19
2 00:22:03
3 00:41:07
4 00:11:54
5 00:21:34

我使用了这段代码:df.groupby([pd.Grouper(key='Duration', freq='5T')]).size()

我发现了以下结果:

Duration
00:01:37 1
00:06:37 0
00:11:37 1
00:16:37 2
00:21:37 1
00:26:37 0
00:31:37 0
00:36:37 1
00:41:37 0
Freq: 5T, dtype: int64

我的预期结果是:

Duration    Counts
00:00:00 0
00:05:00 1
00:10:00 0
00:15:00 1
00:20:00 1
........ ...

我的期望是索引将从 00:00:00 而不是 00:01:37 开始。

或者,显示垃圾桶也对我有用,我的意思是:

Duration   Counts
0-5 1
5-10 0
10-15 1
15-20 1
20-25 2
........ ...

我需要你的帮助。谢谢。

最佳答案

首先,您需要将时间缩短到第 5 分钟。然后简单地算一下。我想这就是您要找的 -

def round_to_5min(t):
""" This function rounds a timedelta timestamp to the nearest 5-min mark"""
t = datetime.datetime(1991,2,13, t.hour, t.minute - t.minute%5, 0)
return t

data['new_col'] = data.Duration.map(round_to_5min).dt.time

关于python - Pandas duration groupby - 以定义的值开始组范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55659417/

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