Python/Pandas/Numpy - 直接计算两个日期之间不包括节假日的工作日数

标签 python numpy pandas

是否有比以下方法更好/更直接的计算方法?

# 1. Set up the start and end date for which you want to calculate the      
# number of business days excluding holidays.

start_date = '01JAN1986'
end_date = '31DEC1987'
start_date = datetime.datetime.strptime(start_date, '%d%b%Y')
end_date = datetime.datetime.strptime(end_date, '%d%b%Y')

# 2. Generate a list of holidays over this period
from pandas.tseries.holiday import USFederalHolidayCalendar
calendar = USFederalHolidayCalendar()
holidays = calendar.holidays(start_date, end_date)
holidays

它给出了一个 pandas.tseries.index.DatetimeIndex

DatetimeIndex(['1986-01-01', '1986-01-20', '1986-02-17', '1986-05-26',
           '1986-07-04', '1986-09-01', '1986-10-13', '1986-11-11',
           '1986-11-27', '1986-12-25', '1987-01-01', '1987-01-19',
           '1987-02-16', '1987-05-25', '1987-07-03', '1987-09-07',
           '1987-10-12', '1987-11-11', '1987-11-26', '1987-12-25'],
          dtype='datetime64[ns]', freq=None, tz=None)

但是你需要一个 numpy busday_count 列表

holiday_date_list = holidays.date.tolist()

然后有假期和没有假期你会得到:

np.busday_count(start_date.date(), end_date.date()) 
>>> 521

np.busday_count(start_date.date(), end_date.date(), holidays = holiday_date_list)
>>> 501

还有一些其他问题略有相似,但通常使用 pandas Series 或 Dataframes(Get business days between start and end date using pandasCounting the business days between two series)

最佳答案

如果将创建的索引放在数据框中,则可以使用 resample填补空白。传递给 .resample() 的偏移量可以包括工作日甚至(自定义)日历之类的内容:

from pandas.tseries.holiday import USFederalHolidayCalendar

C = pd.offsets.CustomBusinessDay(calendar=USFederalHolidayCalendar())

start_date = '01JAN1986'
end_date = '31DEC1987'

(
pd.DataFrame(index=pd.to_datetime([start_date, end_date]))
    .resample(C, closed='right') 
    .asfreq()
    .index  
    .size
) - 1

索引的大小 - 1 然后给我们天数。

关于Python/Pandas/Numpy - 直接计算两个日期之间不包括节假日的工作日数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265711/

相关文章:

python - Pandas :多列合并为一列

python - 如何在python 2.6中打印unicode中文字符串?

python - Numpy 元素乘法(意外的整数溢出)

python - 将 float 转换为 int 并保留空值

python - 映射到 pandas 中的相同数据框列

python - 如何使用正则表达式从字符串中提取前两个字符

python - 用 Python 中的多个 plot.ly 图形绘制图

python - DecisionTreeRegressor 中的 random_state 是什么?

python - 使用 openCV 导出 openGL 纹理时出现异常

python - 为什么Python中的十六进制字节数据是b'\x3 5' being interpreted as b' 5'?