计算列在恢复为 0 之前为正的时间量

Calculate the amount of time that a column was positive before reverting to 0

我有一个 table 包含针对日期时间索引的非负值,如下所示:

                    CapturableSeparation
date    
2021-02-23 18:09:00 0.00
2021-02-23 18:10:00 0.00
2021-02-23 18:11:00 0.04
2021-02-23 18:12:00 0.04
2021-02-23 18:13:00 0.00
... ...
2021-02-25 23:56:00 0.00
2021-02-25 23:57:00 0.91
2021-02-25 23:58:00 0.74
2021-02-25 23:59:00 0.55

我想创建一个 table 非连续 0 之间的时间量(正值在恢复为 0 之前持续存在的时间量),在那些期间以“CapturableSeparation”的平均值作为键控连续的正值。对于可见的数据,table 可能类似于:

                    AvgValue
persistence 
00:02:00            0.04
00:03:00            0.73

其中第一行对应于数据帧开头持续 2 分钟的正值,第二行对应于末尾持续 3 分钟的正值。

应该怎么做?

这是通过使用布尔掩码和 cumsum 识别连续的非零值块来解决问题的一种方法:

m = df['CapturableSeparation'].eq(0)
b = m.cumsum()[~m]
agg_dict = {'persistence': ('date', np.ptp), 
            'avgvalue'   : ('CapturableSeparation', 'mean')}

out = df.groupby(b, as_index=False).agg(**agg_dict)
out['persistence'] += pd.Timedelta(minutes=1)

详情:

比较 CapturableSeparation 列与 0 以创建布尔掩码:

>>> m

0     True
1     True
2    False
3    False
4     True
5     True
6    False
7    False
8    False
Name: CapturableSeparation, dtype: bool

然后在上面的布尔掩码上使用cumsum来识别连续非零值的块:

>>> b

2    2
3    2
6    4
7    4
8    4
Name: CapturableSeparation, dtype: int64

在这些连续的块上对数据帧进行分组,并使用 np.ptp 聚合列 date 并使用 mean:

聚合列 CapturableSeparation
>>> out

      persistence  avgvalue
0 0 days 00:02:00  0.040000
1 0 days 00:03:00  0.733333