Python 时间序列 - 计数周期 below/above 和指定最短持续时间的阈值
Python time series - count periods below/above and threshold for specified minimum duration
在 pandas 时间序列中,我试图找到阈值与持续时间的组合度量。
例如,我们希望周期数 > 5 分钟,其中 ['pct'] 列低于 80
数据框如下所示:
timestamp
pct
27-05-2021 10:11
95
27-05-2021 10:12
94
27-05-2021 10:13
80
27-05-2021 10:14
94
27-05-2021 10:15
80
27-05-2021 10:16
80
27-05-2021 10:17
80
27-05-2021 10:18
80
27-05-2021 10:19
80
27-05-2021 10:20
91
27-05-2021 10:21
NaN
27-05-2021 10:22
80
27-05-2021 10:23
80
27-05-2021 10:24
80
27-05-2021 10:25
80
27-05-2021 10:26
94
因此需要确定 1 个周期(因为我们不关心包括 NaN 值)
我已经从 Ben B 的 post 和 Alain T 那里得到了一些答案:
我附上一张来自微软画图的丑陋图片来说明问题
注意:这是一个很大的数据框,所以我不确定遍历数据框是最好的主意,但非常感谢任何帮助。
您可以对数据框中连续的 80 进行分组,然后使用列表理解检查每组中的条件并获取其长度:
# first is `pct` column's threshold, other is minute threshold for `timestamp`
value_thre = 80
minute_thre = 3
# groupby by consecutive `value_thre`s
grouper = df.groupby(df.pct.le(value_thre).diff().ne(0).cumsum())
# look at the time difference between last and first timestamp
# also ensure no `pct` value exceeds the value threshold
condition = lambda gr: (gr.pct.max() <= value_thre
and gr.timestamp.iloc[-1] - gr.timestamp.iloc[0] > pd.Timedelta(f"{minute_thre} min"))
# filter the grouper and get the length
result = len([g for _, g in grouper if condition(g)])
得到
>>> result
1
在 pandas 时间序列中,我试图找到阈值与持续时间的组合度量。
例如,我们希望周期数 > 5 分钟,其中 ['pct'] 列低于 80
数据框如下所示:
timestamp | pct |
---|---|
27-05-2021 10:11 | 95 |
27-05-2021 10:12 | 94 |
27-05-2021 10:13 | 80 |
27-05-2021 10:14 | 94 |
27-05-2021 10:15 | 80 |
27-05-2021 10:16 | 80 |
27-05-2021 10:17 | 80 |
27-05-2021 10:18 | 80 |
27-05-2021 10:19 | 80 |
27-05-2021 10:20 | 91 |
27-05-2021 10:21 | NaN |
27-05-2021 10:22 | 80 |
27-05-2021 10:23 | 80 |
27-05-2021 10:24 | 80 |
27-05-2021 10:25 | 80 |
27-05-2021 10:26 | 94 |
因此需要确定 1 个周期(因为我们不关心包括 NaN 值)
我已经从 Ben B 的 post 和 Alain T 那里得到了一些答案:
我附上一张来自微软画图的丑陋图片来说明问题
注意:这是一个很大的数据框,所以我不确定遍历数据框是最好的主意,但非常感谢任何帮助。
您可以对数据框中连续的 80 进行分组,然后使用列表理解检查每组中的条件并获取其长度:
# first is `pct` column's threshold, other is minute threshold for `timestamp`
value_thre = 80
minute_thre = 3
# groupby by consecutive `value_thre`s
grouper = df.groupby(df.pct.le(value_thre).diff().ne(0).cumsum())
# look at the time difference between last and first timestamp
# also ensure no `pct` value exceeds the value threshold
condition = lambda gr: (gr.pct.max() <= value_thre
and gr.timestamp.iloc[-1] - gr.timestamp.iloc[0] > pd.Timedelta(f"{minute_thre} min"))
# filter the grouper and get the length
result = len([g for _, g in grouper if condition(g)])
得到
>>> result
1