如何按多列+小时重采样分组,获取最大ProductionSpeed对应列值?
问题描述
现有如下结构的DataFrame:
timestamp Format MachineMode \ 0 2022-08-04 07:49:00+00:00 2000 3.0 1 2022-08-04 07:50:00+00:00 2000 3.0 2 2022-08-04 07:51:00+00:00 2000 3.0 3 2022-08-04 07:52:00+00:00 2000 3.0 4 2022-08-04 07:53:00+00:00 2000 3.0 ... ... ... ... 59825 2022-12-07 06:43:00+00:00 2000 1.0 59826 2022-12-07 06:44:00+00:00 2000 1.0 59827 2022-12-07 06:45:00+00:00 2000 1.0 59828 2022-12-07 06:49:00+00:00 2000 1.0 59829 2022-12-07 06:50:00+00:00 2000 1.0 RecipeName ProductionSpeed TankPressure \ 0 2 LT Fanta 500.001283 4.72 1 2 LT Fanta 500.001650 4.71 2 2 LT Fanta 500.001333 4.72 3 2 LT Fanta 500.001350 4.71 4 2 LT Fanta 308.336100 5.37 ... ... ... ... 59825 2 LT Coca Cola_23K Duo Pack 383.335217 4.80 59826 2 LT Coca Cola_23K Duo Pack 383.335000 4.81 59827 2 LT Coca Cola_23K Duo Pack 306.667767 4.82 59828 2 LT Coca Cola_23K Duo Pack 364.168333 4.53 59829 2 LT Coca Cola_23K Duo Pack 325.833783 4.76 CarouselPressure 0 0.98 1 0.98 2 0.98 3 0.98 4 0.96 ... ... 59825 1.01 59826 0.98 59827 0.99 59828 0.93 59829 0.99
需求:将数据按小时重采样,按Format、MachineMode、RecipeName分组,获取每个分组每小时的最大ProductionSpeed,并展示该速度对应的TankPressure与CarouselPressure值。
已尝试代码:
new_bg1=new_bg.groupby(['RecipeName','Format','MachineMode', pd.Grouper(freq='H')]).ProductionSpeed.agg(['max','idxmax']).reset_index()
问题:无法获取对应的TankPressure和CarouselPressure值。
解决方案
你之前的代码仅针对ProductionSpeed列做聚合,因此无法关联到其他列的数据。以下两种方法可解决该问题:
方法1:通过索引匹配原数据行
先获取每个分组内最大ProductionSpeed对应的行索引,再从原DataFrame中提取完整行数据:
# 确保timestamp为datetime类型 new_bg['timestamp'] = pd.to_datetime(new_bg['timestamp']) # 分组计算每个组内最大ProductionSpeed的行索引 grouped = new_bg.groupby(['RecipeName', 'Format', 'MachineMode', pd.Grouper(key='timestamp', freq='H')]) max_speed_idx = grouped['ProductionSpeed'].idxmax() # 根据索引提取对应行,得到包含所有目标列的结果 result = new_bg.loc[max_speed_idx].reset_index(drop=True)
执行后result将包含每个分组每小时最大ProductionSpeed对应的所有列数据,包括TankPressure和CarouselPressure。
方法2:自定义聚合函数
如果需要更灵活的列控制,可以自定义聚合函数直接返回目标数据:
def extract_max_speed_data(group): # 获取组内ProductionSpeed最大的行 max_row = group.loc[group['ProductionSpeed'].idxmax()] return pd.Series({ 'max_ProductionSpeed': max_row['ProductionSpeed'], 'TankPressure': max_row['TankPressure'], 'CarouselPressure': max_row['CarouselPressure'] }) # 分组应用自定义函数 result = grouped.apply(extract_max_speed_data).reset_index()
该方法可直接指定输出列名和保留字段,结果结构更清晰。
注意:若同一分组小时内存在多个行的ProductionSpeed等于最大值,idxmax会返回第一个出现的行索引。若需处理这种场景,可根据需求调整逻辑(如提取所有最大值行)。
内容的提问来源于stack exchange,提问作者Jahrakal
相关产品推荐
相关产品推荐

