一尘不染

计算间隔中的寄存器数

sql

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

     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,我想为每一行计数在该间隔内“打开”了多少个寄存器。例如,考虑到T = 2hours,这将是输出:

     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的前身,则对于T等于1,我可以每小时创建一个列数,然后将其移位1,然后将结果相加count[i]+ count[i-1]。但是我不知道是否可以将其推广到所需的输出。


阅读 197

收藏
2021-05-16

共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
2021-05-16