计算分钟时间间隔之间的行数 - Python
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算分钟时间间隔之间的行数 - Python相关的知识,希望对你有一定的参考价值。
我想使用groupby函数计算30分钟时间间隔的行数,从第一个单元格向下列计算30分钟间隔。这是我有的:
LOGINID DATE TIME
mickey 1/1/2018 0 days 08:54:00.000000000
mickey 1/1/2018 0 days 08:57:00.000000000
mickey 1/1/2018 0 days 09:01:00.000000000
mickey 1/1/2018 0 days 09:19:00.000000000
mickey 1/1/2018 0 days 09:26:00.000000000
mickey 1/1/2018 0 days 09:41:00.000000000
mickey 1/1/2018 0 days 10:03:00.000000000
mickey 1/1/2018 0 days 11:35:00.000000000
mickey 1/1/2018 0 days 11:36:00.000000000
mickey 1/2/2018 0 days 09:54:00.000000000
mickey 1/2/2018 0 days 10:21:00.000000000
minnie 1/1/2018 0 days 09:00:00.000000000
minnie 1/1/2018 0 days 10:20:00.000000000
minnie 1/1/2018 0 days 10:14:00.000000000
minnie 1/1/2018 0 days 10:51:00.000000000
minnie 1/1/2018 0 days 11:05:00.000000000
minnie 1/1/2018 0 days 11:24:00.000000000
minnie 1/2/2018 0 days 02:20:00.000000000
minnie 1/2/2018 0 days 02:25:00.000000000
minnie 1/2/2018 0 days 02:39:00.000000000
This is what I want:
LOGINID DATE TIME intense_cnt
mickey 1/1/2018 0 days 08:54:00.000000000 4
mickey 1/1/2018 0 days 08:57:00.000000000 4
mickey 1/1/2018 0 days 09:01:00.000000000 3
mickey 1/1/2018 0 days 09:19:00.000000000 3
mickey 1/1/2018 0 days 09:26:00.000000000 2
mickey 1/1/2018 0 days 09:41:00.000000000 2
mickey 1/1/2018 0 days 10:03:00.000000000 1
mickey 1/1/2018 0 days 11:35:00.000000000 2
mickey 1/1/2018 0 days 11:36:00.000000000 2
mickey 1/2/2018 0 days 09:54:00.000000000 2
mickey 1/2/2018 0 days 10:21:00.000000000 1
minnie 1/1/2018 0 days 09:00:00.000000000 1
minnie 1/1/2018 0 days 10:20:00.000000000 2
minnie 1/1/2018 0 days 10:14:00.000000000 2
minnie 1/1/2018 0 days 10:51:00.000000000 2
minnie 1/1/2018 0 days 11:05:00.000000000 2
minnie 1/1/2018 0 days 11:24:00.000000000 1
minnie 1/2/2018 0 days 02:20:00.000000000 3
minnie 1/2/2018 0 days 02:25:00.000000000 3
minnie 1/2/2018 0 days 02:39:00.000000000 3
所以对于第一行,我从8:54开始向下计算30分钟,这是9:24,这将给我总共4行。然后对于第二行,我从8:57向下计算30分钟,这是9:27,这将给我总共4行然后对于第三行,我从9:01向下计数30分钟,这是9:31,这将给我总共3行,依此类推。
谁会知道怎么做?
非常感谢!
答案
不确定你是否也要计算“当前”日期,因为在你的解释中你认为不一致。在我的代码中,您可以通过将>
调整为>=
来轻松更改它。
Code
from datetime import timedelta
from dateutil import parser
import pandas as pd
dates = [
"2018-2-1 08:54:00",
"2018-2-1 08:57:00",
"2018-2-1 09:01:00",
"2018-2-1 09:19:00",
"2018-2-1 09:26:00",
"2018-2-1 09:41:00",
"2018-2-1 10:03:00",
"2018-2-1 11:35:00",
"2018-2-1 11:36:00",
"2018-2-1 09:54:00",
"2018-2-1 10:21:00",
"2018-2-1 09:00:00",
"2018-2-1 10:20:00",
"2018-2-1 10:14:00",
"2018-2-1 10:51:00",
"2018-2-1 11:05:00",
"2018-2-1 11:24:00",
"2018-2-2 02:20:00",
"2018-2-2 02:25:00",
"2018-2-2 02:39:00"]
dates = pd.DataFrame([parser.parse(date) for date in dates])
counts = [
int(dates[(dates > date)
& (dates <= (date + timedelta(minutes=30)))].count())
for date in dates[0]
]
Result
[4, 4, 2, 2, 2, 2, 3, 1, 0, 4, 1, 3, 1, 2, 1, 2, 2, 2, 1, 0]
以上是关于计算分钟时间间隔之间的行数 - Python的主要内容,如果未能解决你的问题,请参考以下文章