Python 如何计算时间序列中高于/低于阈值的连续周期?
我有一个为期一年的值数据集,我希望检测和统计超过/低于预先指定阈值的连续值的周期。我只想返回连续高于/低于阈值的每个周期的长度。我在网上找到的代码几乎完全符合我的要求(如下所示,函数名为“fire\u seasure\u length”),除了在数据集结束前(年底)返回最后一个连续周期有困难之外 我认为这个问题是因为只有当一系列值从高于(低于)阈值翻转到低于(高于)阈值时,才会报告连续值的周期 以下是我用来计算连续高于/低于阈值周期的函数:Python 如何计算时间序列中高于/低于阈值的连续周期?,python,for-loop,count,Python,For Loop,Count,我有一个为期一年的值数据集,我希望检测和统计超过/低于预先指定阈值的连续值的周期。我只想返回连续高于/低于阈值的每个周期的长度。我在网上找到的代码几乎完全符合我的要求(如下所示,函数名为“fire\u seasure\u length”),除了在数据集结束前(年底)返回最后一个连续周期有困难之外 我认为这个问题是因为只有当一系列值从高于(低于)阈值翻转到低于(高于)阈值时,才会报告连续值的周期 以下是我用来计算连续高于/低于阈值周期的函数: def fire_season_length(ts,
def fire_season_length(ts, threshold):
ntot_ts = ts.count() #total number of values in ts (timeseries)
n_gt_threshold = ts[ts >= threshold].count() #number of values greater than threshold
type_day = 0 #below threshold
type_day = 1 #meets or exceeds threshold
type_prev_day = 0 #initialize first day
storage_n_cons_days = [[],[]] #[[cons days above threshold], [cons days below threshold]]
n_cons_days = 0
for cur_day in ts: #current day in timeseries
if cur_day >= threshold:
type_cur_day = 1
if type_cur_day == type_prev_day: #if same as current day
n_cons_days += 1
else: #if not same as current day
storage_n_cons_days[1].append(n_cons_days)
n_cons_days = 1
type_prev_day = type_cur_day
else:
type_cur_day = 0
if type_cur_day == type_prev_day:
n_cons_days += 1
else:
storage_n_cons_days[0].append(n_cons_days)
n_cons_days = 1
type_prev_day = type_cur_day
return ntot_ts, n_gt_threshold, storage_n_cons_days
这是通过函数运行timeseries时的输出我对绘图进行了注释,以显示有7个连续值周期,但返回的数组[[13185,30]、[24,78,12](表示[[periods Upper threshold]、[periods Down threshold]])只列出了6个这样的周期。输出中似乎没有报告周期7,这与我在此函数中测试的其他timeseries的输出一致
因此,我的问题是:如何让代码返回连续值的最后一个周期,即使值序列没有翻转为另一个符号(高于/低于阈值)?您可以使用accumulate()和Counter()的组合来实现这一点: 示例输出:
data [99, 49, 84, 69, 27, 88, 35, 43, 3, 48, 80, 14, 32, 97, 78]
above [1, 2, 1, 1, 2]
below [1, 1, 4, 2]
其工作方式如下:
- 首先确定发生上下变化的位置李>
- 状态更改由True(1)标识,未更改的位置为False(0)李>
- 这些1和0的累积和将产生一系列不同的变化值,这些变化值在没有状态变化的位置重复出现李>
- 然后使用计数器类计算每个重复值出现的次数。这对应于按不同状态更改细分的连续状态数李>
- 对计数器进行排序可恢复状态更改的时间顺序李>
- 根据第一项的状态,偶数值将全部对应于高于或低于状态,而奇数值将是相反的状态
data [99, 49, 84, 69, 27, 88, 35, 43, 3, 48, 80, 14, 32, 97, 78]
above [1, 2, 1, 1, 2]
below [1, 1, 4, 2]