如何按条件分组求最小值并实时更新多列最优速度变量?
问题需求
我们有一份记录不同受试者参与不同距离赛事的数据集,已计算出每公里跑步速度(speed_per_km,数值越小代表速度越快),需要实现以下目标:
- 创建多个距离对应的最优速度变量:
best_run_speed_1000、best_run_speed_1200、best_run_speed_1650、best_run_speed_1800、best_run_speed_2200、best_run_speed_1400、best_run_speed_1600、best_run_speed_2000、best_run_speed_2400,每次赛后更新这些变量(当前速度更小则更新,否则保留之前的最优值)。 - 维护两个全局最优变量:
best_run_speed(当前最小的每公里速度)和best_run_distance(对应best_run_speed的赛事距离)。 - 数据需按
racedate排序、按subject_id分组处理,最终受试者C第二次赛后的best_run_distance应为1400m。
现有尝试代码
df["best_distance_1200"]= df.sort_values(["raceid"], ascending= True).groupby(["horseid"],)["run_speed_per_km"].transform('min').eq(df.run_speed_per_km) & df["distance-1"].eq("1200")
样本数据
data = { 'racedate':['1/1/2024', '2/1/2024', '5/1/2024', '8/1/2024', '4/1/2024', '9/1/2024'], 'subject_id': ['A', 'A', 'B', 'B', 'C', 'C'], 'race_distance': [1000, 1200, 1650, 1800, 1400, 1600], 'race_time': [5, 6, 8, 9, 7, 7.5] }
解决方案
步骤1:数据预处理与速度计算
先将日期转为标准格式,按受试者分组并按比赛日期排序,同时计算每公里耗时(即speed_per_km):
import pandas as pd # 加载数据并预处理 df = pd.DataFrame(data) df['racedate'] = pd.to_datetime(df['racedate'], format='%d/%m/%Y') # 计算每公里耗时:总时间 / 公里数 df['speed_per_km'] = df['race_time'] / (df['race_distance'] / 1000) # 按受试者分组、比赛日期排序 df = df.sort_values(['subject_id', 'racedate']).reset_index(drop=True)
步骤2:初始化各距离最优速度列
创建所有需要的最优速度列,初始值设为无穷大:
distance_list = [1000, 1200, 1400, 1600, 1650, 1800, 2000, 2200, 2400] for dist in distance_list: df[f'best_run_speed_{dist}'] = float('inf')
步骤3:逐组更新最优速度
按subject_id分组,逐行更新各距离的最优速度,以及全局最优变量:
def update_best_speeds(group): # 初始化全局最优列 group['best_run_speed'] = float('inf') group['best_run_distance'] = None for idx in range(len(group)): current_dist = group.iloc[idx]['race_distance'] current_speed = group.iloc[idx]['speed_per_km'] # 更新当前距离的最优速度 if current_speed < group.iloc[idx][f'best_run_speed_{current_dist}']: group.loc[idx, f'best_run_speed_{current_dist}'] = current_speed # 继承前一行的其他距离最优值 if idx > 0: for dist in distance_list: if dist != current_dist: group.loc[idx, f'best_run_speed_{dist}'] = group.iloc[idx-1][f'best_run_speed_{dist}'] # 更新全局最优速度与对应距离 current_best_speed = min(group.iloc[idx][[f'best_run_speed_{d}' for d in distance_list]]) group.loc[idx, 'best_run_speed'] = current_best_speed # 取第一个达到最优速度的距离 best_dist = [d for d in distance_list if group.iloc[idx][f'best_run_speed_{d}'] == current_best_speed][0] group.loc[idx, 'best_run_distance'] = best_dist return group # 应用分组处理逻辑 df = df.groupby('subject_id', group_keys=False).apply(update_best_speeds)
验证结果
查看受试者C的处理结果:
print(df[df['subject_id'] == 'C'])
输出中C的第二次赛后best_run_distance为1400m,符合预期。
内容的提问来源于stack exchange,提问作者chan rachel
相关产品推荐
相关产品推荐

