【问题标题】:Count on a rolling time window in pandas依靠 pandas 的滚动时间窗口
【发布时间】:2020-07-13 01:28:06
【问题描述】:

我正在尝试返回关于(移动)固定点的时间窗口的计数。

它试图随时了解仪器的状况,作为它之前的使用的函数。

因此,如果仪器在 12.05pm、12.10、12.15、12.30、12.40 和 1pm 使用,则使用次数为:

12.05 -> 1(最后一小时一次)

12.10 -> 2

12.15 -> 3

12.30 -> 4

12.40 -> 5

1.00 -> 6

...但是让我们说在 1.06 恢复使用: 1.06 -> 6 这不会增加计数,因为第一次运行是一个多小时前。

如何计算此计数并将其附加为一列?

感觉这是一个 groupby/aggregate/count,可能在 lambda 函数中使用 timedeltas,但我不知道从哪里开始。

我也希望能够使用时间窗口,所以不仅仅是过去的一小时,而是实例周围的一小时,即 + 和 -30 分钟。

以下代码给出了一个起始数据框:

s = pd.Series(pd.date_range('2020-1-1', periods=8000, freq='250s'))
df = pd.DataFrame({'Run time': s})
df_sample = df.sample(6000)
df_sample = df_sample.sort_index()

我找到的最好的帮助(公平地说,我通常可以从逻辑中破解)是Distinct count on a rolling time window,但这次我没有成功。

谢谢

【问题讨论】:

  • 那么,问题是什么?
  • @manu190466 我已经在编辑中澄清了谢谢
  • 什么时候增加计数,什么时候不增加计数?
  • 这取决于时间窗口
  • 因此,如果您在 1.12 进行测量,则计数不会增加,因为您已经在一个多小时前进行了跑步。那么计数器将永远停留在 6 点?

标签: python pandas pandas-groupby timedelta


【解决方案1】:

我之前用DataFrame.rolling 函数做过类似的事情: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html

所以对于您的数据集,首先您需要将索引更新为日期时间字段,然后您可以执行您需要的分析,因此从您的代码继续:

s = pd.Series(pd.date_range('2020-1-1', periods=8000, freq='250s'))
df = pd.DataFrame({'Run time': s})
df_sample = df.sample(6000)
df_sample = df_sample.sort_index()

# Create a value we can count
df_sample('Occurrences') = 1

# Set the index to the datetime element
df_sample = df_sample.set_index('Run time')

# Use Pandas rolling method, 3600s = 1 Hour
df_sample['Occurrences in Last Hour'] = df_sample['Occurrences'].rolling('3600s').sum()

df_sample.head(15)

                     Occurrences  Occurrences in Last Hour
Run time                                                   
2020-01-01 00:00:00            1                       1.0
2020-01-01 00:04:10            1                       2.0
2020-01-01 00:08:20            1                       3.0
2020-01-01 00:12:30            1                       4.0
2020-01-01 00:16:40            1                       5.0
2020-01-01 00:25:00            1                       6.0
2020-01-01 00:29:10            1                       7.0
2020-01-01 00:37:30            1                       8.0
2020-01-01 00:50:00            1                       9.0
2020-01-01 00:54:10            1                      10.0
2020-01-01 00:58:20            1                      11.0
2020-01-01 01:02:30            1                      11.0
2020-01-01 01:06:40            1                      11.0
2020-01-01 01:15:00            1                      10.0
2020-01-01 01:19:10            1                      10.0

您需要将索引设置为日期时间元素以使用时基窗口,否则您只能使用与行数对应的整数值。

【讨论】:

  • 抱歉,我以为我会留下评论 - 谢谢你,这很好,可以完成工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 2018-01-28
  • 2018-12-17
相关资源
最近更新 更多