You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个DataFrame按ID和最近日期匹配生成Attendance列

实现方案

方法1:无额外中间列实现

不需要新增额外临时列,所有逻辑封装在匹配函数内,仅最终生成你需要的Attendance列,代码如下:

import pandas as pd

# 预处理df2的日期列,转成datetime格式备用
df2_date_cols = pd.to_datetime(df2.columns[1:], format='%m/%d/%Y')
df2_date_names = df2.columns[1:]

def match_attendance(row):
    current_id = row['ID']
    current_date = pd.to_datetime(row['Date'], format='%m/%d/%Y')
    # 取同ID的df2行数据
    same_id_row = df2[df2['ID'] == current_id].iloc[0]
    # 处理12/31优先匹配下一年1月1日的特殊规则
    next_day = current_date + pd.Timedelta(days=1)
    if next_day in df2_date_cols:
        target_col = df2_date_names[df2_date_cols.get_loc(next_day)]
    else:
        # 计算日期差取最小的对应列
        diff = abs(df2_date_cols - current_date)
        target_col = df2_date_names[diff.argmin()]
    return same_id_row[target_col]

df1['Attendance'] = df1.apply(match_attendance, axis=1)

运行后得到的df1结果完全符合匹配规则:

IDDateAttendance
09002/01/202114
110101/31/202110
23012/31/202113

补充说明

  • 完全可以不创建额外列,上述方案就没有产生任何临时中间列,所有计算都在函数内部完成。
  • 如果数据量较大(十万行以上),可以提前把df2转成{ID:{日期:数值}}的嵌套字典做缓存,避免每行都过滤df2,运行速度会提升数倍。

内容的提问来源于stack exchange,提问作者Sriram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:54:04