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

合并两个DataFrame时原含NaT的行合并后关联字段设为NaN

解决方法

核心逻辑是先以df1为基准左连接df2的对应字段,再对df1中other_date为NaT的行单独处理type值:

  1. 执行左连接,关联键为ID和updated_date,仅从df2中取出需要的type字段即可,避免两个表的other_date字段冲突
import pandas as pd

# 左连接完整保留df1的所有行
merged_df = df1.merge(
    df2[["ID", "updated_date", "type"]],
    on=["ID", "updated_date"],
    how="left"
)
  1. 将原df1中other_date为NaT的行对应的type字段设置为空值
merged_df.loc[merged_df["other_date"].isna(), "type"] = pd.NA

结果验证

执行上述代码后输出merged_df即可得到预期结果:

ID updated_date other_date type
0  11   2019-04-03 2019-04-09    C
1  11   2019-05-02 2019-05-14    C
2  11   2019-05-20 2019-06-05    D
3  11   2019-03-03        NaT <NA>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:36:03