以熊猫为单位的滚动时间窗口计数

问题描述 投票:0回答:1

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

试图根据使用之前的使用情况随时了解仪器的状况。

因此,如果仪器在下午12.05、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这不会增加计数,因为第一次运行是在一个小时之前。

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

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

我也希望能够与时间窗口一起播放,所以不仅是过去的一个小时,还包括一个实例周围的小时,即+和-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,但这次我没有设法解决。

谢谢

python pandas pandas-groupby timedelta
1个回答
0
投票

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

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

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

您需要将索引设置为datetime元素才能利用时基窗口,否则只能使用与行数相对应的整数值。

© www.soinside.com 2019 - 2024. All rights reserved.