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

如何在Pandas函数中将日期差替换为扣除节假日的工作日差?

替换自然日差为英国工作日差的简便方法

不需要自定义访问器,直接利用你已有的CustomBusinessDay对象或者numpy的busday_count就能实现,两种简便方案如下:

方案一:利用pandas的CustomBusinessDay偏移量除法

假设你已经定义好英国工作日规则的CustomBusinessDay实例(比如命名为uk_bd),直接将日期差除以这个偏移量即可得到工作日数:

# 替换原代码中的s = x[~m].loc[k:, 'Date'].sub(v).dt.days
s = (x[~m].loc[k:, 'Date'] - v) / uk_bd
  • 计算结果为浮点数,若需要整数可追加.astype(int)(若需向上/向下取整可改用np.ceil()或np.floor())
  • 原理:Timedelta类型除以CustomBusinessDay实例会自动按设定的工作日规则计算间隔天数

方案二:利用numpy的busday_count

直接调用np.busday_count,传入你的英国节假日列表和工作日掩码,更适合批量日期计算:

import numpy as np

# 将日期转换为numpy datetime64格式
start_date = v.to_numpy().astype('datetime64[D]')
end_dates = x[~m].loc[k:, 'Date'].to_numpy().astype('datetime64[D]')

# 替换原代码中的s
s = np.busday_count(start_date, end_dates, holidays=uk_holidays, weekmask='Mon Tue Wed Thu Fri')
  • 此方法直接返回整数类型的工作日差,无需额外类型转换
  • 需确保你已持有uk_holidays列表(即定义CustomBusinessDay时用的节假日集合)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 01:50:25