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

Python如何基于pandas实现多日期字段的DateDuration条件计算

多层嵌套日期间隔计算实现方案

实现思路

原有代码仅转换了2个日期列的类型,且条件未覆盖全部嵌套分支。使用np.select按优先级从高到低排列判断条件即可无嵌套实现全部逻辑:np.select会按顺序匹配条件,命中第一个符合的条件后直接返回对应结果,天然适配多层判断逻辑。
判断优先级严格匹配给定规则:

  • 优先级1:SecondDate与FirstDate间隔≥28天 → 取两日期差值
  • 优先级2:SecondDate间隔<28天,且ThirdDate为空 → 取SecondDate与FirstDate差值
  • 优先级3:SecondDate间隔<28天,ThirdDate非空,且ThirdDate与FirstDate间隔≥28天 → 取ThirdDate与FirstDate差值
  • 优先级4:SecondDate间隔<28天,ThirdDate非空,ThirdDate间隔<28天,且FourthDate为空 → 取ThirdDate与FirstDate差值
  • 优先级5:剩余情况(SecondDate间隔<28天、ThirdDate非空、ThirdDate间隔<28天、FourthDate非空)→ 取FourthDate与FirstDate差值

完整可运行代码

import pandas as pd
import numpy as np

# 全部日期列统一转换为datetime类型,空值自动转为NaT
df['FirstDate'] = pd.to_datetime(df['FirstDate'])
df['SecondDate'] = pd.to_datetime(df['SecondDate'])
df['ThirdDate'] = pd.to_datetime(df['ThirdDate'])
df['FourthDate'] = pd.to_datetime(df['FourthDate'])

# 计算各日期与FirstDate的间隔天数,NaT对应的天数为NaN
x = (df['SecondDate'] - df['FirstDate']).dt.days
y = (df['ThirdDate'] - df['FirstDate']).dt.days
z = (df['FourthDate'] - df['FirstDate']).dt.days

# 按优先级排列条件和对应返回值
condlist = [
    x >= 28,
    (x < 28) & (pd.isna(y)),
    (x < 28) & (~pd.isna(y)) & (y >= 28),
    (x < 28) & (~pd.isna(y)) & (y < 28) & (pd.isna(z)),
    (x < 28) & (~pd.isna(y)) & (y < 28) & (~pd.isna(z))
]

choicelist = [
    x,
    x,
    y,
    y,
    z
]

# 生成最终计算列
df['DateDuration'] = np.select(condlist, choicelist)

结果验证

用提供的示例数据运行后,计算结果与给定的DateDuration列完全匹配:

IDFirstDateSecondDateThirdDateFourthDateDateDuration
29143002021-09-232021-10-072021-11-292021-12-2067
38934612021-09-082021-10-062022-04-07211
43430752021-06-232021-09-2796
43477722021-06-232021-09-2796
45519632021-08-022021-10-142022-03-1173
48933242021-09-302021-10-012022-03-032022-03-10154
52399912021-06-242021-08-262021-09-252022-02-0363
84549472021-09-282021-10-057
85813902021-09-272022-03-212022-03-25175
87637662021-09-202021-10-042021-12-0980
91441852021-06-182021-06-235
99676852021-09-132021-10-292022-02-072022-03-2346
113675602021-08-312021-09-282021-10-212022-02-1151

若运行中遇到28天临界值匹配不符合预期,检查Excel内间隔计算是否包含日期当天,对应调整判断阈值即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 10:51:34