以Pandas为单位计算工资天数

2024-09-27 21:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个自定义日历:

holidays_list = [...]  # list of all weekends and holidays for needed time period

class MyBusinessCalendar(AbstractHolidayCalendar):
    start_date = datetime(2011, 1, 1)
    end_date = datetime(2017, 12, 31)
    rules = [
        Holiday(name='Day Off', year=d.year, month=d.month, day=d.day) for d in holidays_list
    ]

cal = MyBusinessCalendar()

我知道发薪日是每个月的第5天和第20天,如果这两天是休息日,则是前一个工作日。 因此我采取

bus_day = CustomBusinessDay(calendar=cal)
r = pd.date_range('2011-01-01', '2017-12-31', freq=bus_day)

如果是发薪日,我想从r开始计算每一天。我怎么能得到这个?你知道吗


Tags: offordatetimedateholidaysallyearlist
1条回答
网友
1楼 · 发布于 2024-09-27 21:26:55

工资日列表(美式英语中的工资日)由您定义为:

the 5th and the 20th days of each month or the previous business days if these ones are days off

要使用假日日历以编程方式生成发薪日列表,可以生成每月6日和每月21日的列表:

dates = [date(year, month, 6) for month in range(1, 13)] +
    [date(year, month, 21) for month in range(1, 13)]

然后得到上一个工作日,即偏移量=-1。我会用这个:

np.busday_offset(dates, -1, roll='forward', holidays=my_holidays)

我使用numpy.busday_offset而不是Pandas来做偏移的原因是它是矢量化的,运行速度非常快,而Pandas busday偏移逻辑非常慢。如果约会的次数少,那就不重要了。如果需要,您仍然可以使用Pandas生成假日列表。你知道吗

请注意,roll='forward'是因为您希望逻辑是,如果第6个工作日是在周末或假日,则向前滚动到第7个或第8个工作日,然后从那里抵消-1个工作日以获得发薪日。你知道吗

相关问题 更多 >

    热门问题