Python DataFrame按customer_id分组统计工单首提日期、最大操作及解决日期
实现方案
不需要使用self join,直接通过Pandas的分组聚合能力即可实现该需求,具体步骤如下:
前置处理
首先需要将3个日期字段转换为datetime类型,避免字符串比较大小出现逻辑错误:
import pandas as pd # 假设原始数据已经读取为DataFrame,变量名为df date_cols = ['issue_date', 'action_date', 'resolve_date'] for col in date_cols: # 按日-月-年格式解析,空值自动转为NaT df[col] = pd.to_datetime(df[col], format='%d-%m-%Y', errors='coerce')
分组聚合
按customer_id分组后,对每个分组的字段按业务规则聚合即可:
def customer_agg(group): # 判断当前客户是否所有工单都已解决 all_resolved = (group['status'] == 'resolved').all() # 按规则计算各字段值 return pd.Series({ "status": "resolved" if all_resolved else "in-progress" if "in-progress" in group["status"].values else "submitted", "issue_date": group["issue_date"].min(), "action_date": group["action_date"].max(), "resolve_date": group["resolve_date"].max() if all_resolved else pd.NA }) # 执行分组聚合 result_df = df.groupby("customer_id", as_index=False).apply(customer_agg) # 如果需要把日期转回字符串格式,空值显示为NULL,可加以下代码 for col in date_cols: result_df[col] = result_df[col].dt.strftime("%d-%m-%Y").fillna("NULL")
结果说明
执行完成后result_df的输出格式和你给出的预期示例完全一致,逻辑完全符合业务规则:
- 所有工单都为resolved的客户,resolve_date取最大的解决日期,状态为resolved
- 存在未解决工单的客户,resolve_date显示为NULL,状态优先取in-progress,没有in-progress则取submitted
- 日期字段都按要求取对应极值
内容的提问来源于stack exchange,提问作者king
相关产品推荐
相关产品推荐

