Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计数间隔中的寄存器数_Python_Sql_Pandas_Time Series - Fatal编程技术网

Python 计数间隔中的寄存器数

Python 计数间隔中的寄存器数,python,sql,pandas,time-series,Python,Sql,Pandas,Time Series,我想我最好通过一个例子来说明我想要实现的目标。假设我有这个数据帧: time 0 2013-01-01 12:56:00 1 2013-01-01 12:00:12 2 2013-01-01 10:34:28 3 2013-01-01 09:34:54 4 2013-01-01 08:34:55 5 2013-01-01 16:35:19 6 2013-01-01 16:35:30 我想,给定一个间隔T,count,对于每一行,

我想我最好通过一个例子来说明我想要实现的目标。假设我有这个数据帧:

     time
0     2013-01-01 12:56:00
1     2013-01-01 12:00:12
2     2013-01-01 10:34:28
3     2013-01-01 09:34:54
4     2013-01-01 08:34:55
5     2013-01-01 16:35:19
6     2013-01-01 16:35:30
我想,给定一个间隔T,count,对于每一行,有多少寄存器在该间隔内被“打开”。例如,考虑到T=2小时,这将是输出:

     time                  count
0     2013-01-01 12:56:00  1     # 12:56-2 = 10:56 -> 1 register between [10:56, 12:56)
1     2013-01-01 12:00:12  1 
2     2013-01-01 10:34:28  2     # 10:34:28-2 = 8:34:28 -> 2 registers between [8:34:28, 10:34:28) 
3     2013-01-01 09:34:54  1
4     2013-01-01 08:34:55  0
5     2013-01-01 16:35:19  0
6     2013-01-01 16:35:30  1

我想知道如何使用熊猫获得这个结果。例如,如果我只考虑dt.hour acessor,对于T等于1,我可以创建一个每小时的列计数,然后将其移位1,将
count[I]+count[I-1]
的结果相加。但我不知道是否可以将其推广到所需的输出。

这里的想法是将所有寄存器打开时间标记为+1,将所有寄存器关闭时间标记为-1。然后按时间排序,并对+/-1值进行累积求和,以在给定时间打开计数

# initialize interval start times as 1, end times as -1
start_times= df.assign(time=df['time'] - pd.Timedelta(hours=2), count=1)
all_times = start_times.append(df.assign(count=-1), ignore_index=True)

# sort by time and perform a cumulative sum get the count of overlaps at a given time
# (subtract 1 since you don't want to include the current value in the overlap)
all_times = all_times.sort_values(by='time')
all_times['count'] = all_times['count'].cumsum() - 1

# reassign to the original dataframe, keeping only the original times
df['count'] = all_times['count']
结果输出:

                 time  count
0 2013-01-01 12:56:00      1
1 2013-01-01 12:00:12      1
2 2013-01-01 10:34:28      2
3 2013-01-01 09:34:54      1
4 2013-01-01 08:34:55      0
5 2013-01-01 16:35:19      0
6 2013-01-01 16:35:30      1

我不明白你是怎么定义这些时间间隔的。您如何在12:56之前的2小时内获得
[10:56,12:45]
,而不是
[10:56,12:56)
?您提出的解决方案是如何工作的?如果您按小时计算,这意味着12:56和12:04将在同一个桶中结束,您将无法区分12:56之前的两个小时和12:04之前的两个小时,它们都将包括10:34打开的一个,尽管这是唯一正确的(我想)对于后者。你说得对,@abarnert。按小时分组行就行了。很好!+1非常好。我必须说,我很高兴你的解决方案,我很难理解逻辑。Rs.@pceccon:oops,我在我的旧解决方案中切换了间隔开始/结束逻辑(我认为“时间”是间隔开始,但实际上是结束).修改以更正此逻辑。