pandas:每个日期时间(索引)集群的最大列值,集群内距离 <= N 分钟



如果数据帧有一个日期时间索引,在本例中有6个集群(集群在这里被定义为没有两个相邻行的日期时间差>10分钟的行(,我如何选择数据帧的6行,这些行在这6个集群中的每一个集群中都具有最大列值?

这是输入数据帧:

throughput_ins
ts                                                        
2021-05-03 08:45:00-07:00            16.0
2021-05-03 08:46:00-07:00            16.0
2021-05-03 08:47:00-07:00            17.0
2021-05-03 12:30:00-07:00            11.0
2021-05-03 12:32:00-07:00            12.0
2021-05-03 12:34:00-07:00            13.0
2021-05-03 12:36:00-07:00            16.0
2021-05-03 13:01:00-07:00            13.0
2021-05-03 13:02:00-07:00            17.0
2021-05-03 13:06:00-07:00            24.0
2021-05-03 13:07:00-07:00            14.0
2021-05-03 14:48:00-07:00            17.0
2021-05-03 14:49:00-07:00            15.0
2021-05-03 14:50:00-07:00            18.0
2021-05-03 14:58:00-07:00            24.0
2021-05-03 14:59:00-07:00            26.0
2021-05-03 15:00:00-07:00            27.0
2021-05-03 15:04:00-07:00            31.0
2021-05-03 15:08:00-07:00            39.0
2021-05-03 15:09:00-07:00            34.0
2021-05-03 15:10:00-07:00            28.0
2021-05-03 15:58:00-07:00            10.0
2021-05-03 16:00:00-07:00            11.0
2021-05-03 17:20:00-07:00            13.0
2021-05-03 17:21:00-07:00            18.0
2021-05-03 17:22:00-07:00            17.0

这是预期的输出数据帧:

throughput_ins
ts                                                        
2021-05-03 08:47:00-07:00            17.0
2021-05-03 12:36:00-07:00            16.0
2021-05-03 13:06:00-07:00            24.0
2021-05-03 15:08:00-07:00            39.0
2021-05-03 16:00:00-07:00            11.0
2021-05-03 17:21:00-07:00            18.0

我认为使用df.groupby+iloc会是一种方式,但我不确定如何对adjacent rows < 10 minutes部分进行编码。

使用条件的cumsum()查找块,然后使用groupby().idxmax查找具有最大值的行:

blocks = df.index.to_series().diff().gt(pd.Timedelta('10T')).cumsum()
max_rows = df.groupby(blocks)['throughput_ins'].idxmax()
df.loc[max_rows]

输出:

throughput_ins
ts                                       
2021-05-03 08:47:00-07:00            17.0
2021-05-03 12:36:00-07:00            16.0
2021-05-03 13:06:00-07:00            24.0
2021-05-03 15:08:00-07:00            39.0
2021-05-03 16:00:00-07:00            11.0
2021-05-03 17:21:00-07:00            18.0

最新更新