基于stud_id和prod_id分组,按列顺序查找DataFrame中≥50阈值的首个值并匹配对应日期的实现方案
解决方案
我来帮你实现需求:按stud_id和prod_id分组后,在指定阈值列中按顺序找到首个≥50的记录,并匹配对应日期。以下是完整的代码和说明:
步骤1:数据加载与预处理
首先加载数据并将日期列转换为datetime类型,避免后续日期匹配出现问题:
import pandas as pd import numpy as np # 从剪贴板加载数据 df = pd.read_clipboard() # 将日期列转换为datetime类型 date_columns = ['ques_date', 'inv_date', 'bkl_date', 'accu_date'] df[date_columns] = df[date_columns].apply(pd.to_datetime)
步骤2:定义分组处理函数
创建一个函数,用于处理每个分组:按指定列顺序(upto_inv_threshold→upto_bkl_threshold→upto_accu_threshold)查找首个≥50的值,并返回对应日期:
def get_first_fifty_date(group): # 定义阈值列与对应日期列的映射(按优先级顺序) col_date_mapping = [ ('upto_inv_threshold', 'inv_date'), ('upto_bkl_threshold', 'bkl_date'), ('upto_accu_threshold', 'accu_date') ] # 按顺序遍历每个阈值列 for threshold_col, date_col in col_date_mapping: # 筛选当前列中≥50的行 mask = group[threshold_col] >= 50 if mask.any(): # 获取首个符合条件的行索引 first_match_idx = mask.idxmax() # 返回对应日期 return group.loc[first_match_idx, date_col] # 如果所有列都没有符合条件的值,返回空时间值 return pd.NaT
步骤3:分组执行并生成结果
使用groupby结合自定义函数处理数据,得到最终结果:
# 按stud_id和prod_id分组,执行函数 result = df.groupby(['stud_id', 'prod_id'], as_index=False).apply(get_first_fifty_date) # 重命名结果列 result.columns = ['stud_id', 'prod_id', 'fifty_pct_date'] # 查看结果 print(result)
输出结果
运行上述代码后,你会得到符合预期的输出:
stud_id prod_id fifty_pct_date 0 101 12 2011-10-22
代码逻辑说明
- 函数
get_first_fifty_date按指定优先级遍历阈值列,确保先检查upto_inv_threshold,再检查upto_bkl_threshold,最后是upto_accu_threshold。 mask.idxmax()会返回第一个值为True的行索引(因为True在数值上等于1,False等于0,idxmax会取第一个最大值的位置),保证找到的是首个符合条件的记录。- 如果所有列都没有≥50的值,会返回
pd.NaT(时间类型的空值),方便后续处理。
内容的提问来源于stack exchange,提问作者The Great
相关产品推荐
相关产品推荐

