能否为pandas DataFrame编写双变量for循环计算用户首尾体重差
问题解法
最优实现(无需手动写循环)
直接用pandas内置的分组聚合逻辑即可完成计算,不需要提前单独计算每个用户的最早最晚日期,代码更简洁、执行效率更高:
def calc_weight_change(group): # 对单个用户的所有记录按日期升序排序 sorted_records = group.sort_values('date', ignore_index=True) # 首行是最早记录,末行是最晚记录 earliest_weight = sorted_records.loc[0, 'weight'] latest_weight = sorted_records.loc[sorted_records.index[-1], 'weight'] return pd.Series([earliest_weight, latest_weight, latest_weight - earliest_weight], index=['earliest_weight', 'latest_weight', 'weight_diff']) # 按用户Id分组计算差值 result = weight_info.groupby('user_Id', as_index=False).apply(calc_weight_change)
若要沿用现有逻辑实现双变量循环
你已经生成了和用户ID列表长度一一对应的最早、最晚日期列表,直接用zip函数绑定三个列表同步遍历即可:
weight_diff_result = [] # 同步遍历用户ID、对应最早日期、对应最晚日期 for uid, e_date, l_date in zip(Id_list, earliest_date, latest_date): # 匹配对应用户+最早日期的体重 e_weight = weight_info[(weight_info['user_Id']==uid) & (weight_info['date']==e_date)]['weight'].iloc[0] # 匹配对应用户+最晚日期的体重 l_weight = weight_info[(weight_info['user_Id']==uid) & (weight_info['date']==l_date)]['weight'].iloc[0] weight_diff_result.append(l_weight - e_weight)
- 如果单个用户同一天存在多条体重记录,可根据业务需求调整取值逻辑,比如取当日均值、当日第一条记录即可。
内容的提问来源于stack exchange,提问作者Mario W
相关产品推荐
相关产品推荐

