【问题标题】:Count number of registers in interval统计区间内的寄存器数
【发布时间】:2018-08-20 18:18:42
【问题描述】:

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

     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

我想知道如何使用 pandas 获得此结果。如果我只考虑 dt.hour 存取器,例如 T 等于 1,我可以每小时创建一个列计数,然后将其移动 1,将count[i] + count[i-1] 的结果相加。但我不知道是否可以将其概括为所需的输出。

【问题讨论】:

  • 我不明白你是如何定义这些间隔的。如何在 12:56 前的 2 小时内获得 [10:56, 12:45],而不是 [10:56, 12:56)?
  • 您提出的解决方案是如何工作的?如果您按小时计算,这意味着 12:56 和 12:04 最终将在同一个桶中,您将无法区分 12:56 之前的 2 小时和 2 小时之前到 12:04——他们都将包括在 10:34 开放的那个,尽管这仅对后者是正确的(我认为)。
  • 你是对的,@abarnert。它只是按小时对行进行分组。

标签: python sql pandas time-series


【解决方案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

【讨论】:

  • 太棒了! +1 非常非常好。
  • 我不得不说,我很高兴你的解决方案,我很难理解逻辑。卢比。
  • @pceccon:哎呀,我在旧解决方案中切换了间隔开始/结束逻辑(认为“时间”是间隔开始,但它真的是结束)。已修改以纠正此逻辑。
猜你喜欢
  • 2012-06-08
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 2012-04-24
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多