如何添加日期(节假日除外)中的工作日
我有一个带有start_date列和add_days列(= 10)的数据框(df).我想创建target_date (= start_date + add_days)
,不包括周末和节假日(假期作为数据框).
I have a dataframe (df) with start_date column's and add_days column's (=10). I want to create target_date (=start_date + add_days)
excluding week-end and holidays (holidays as dataframe).
我做了一些研究,然后尝试了.
I do some research and I try this.
from datetime import date, timedelta
import datetime as dt
df["star_date"] = pd.to_datetime(df["star_date"])
Holidays['Date_holi'] = pd.to_datetime(Holidays['Date_holi'])
def date_by_adding_business_days(from_date, add_days, holidays):
business_days_to_add = add_days
current_date = from_date
while business_days_to_add > 0:
current_date += datetime.timedelta(days=1)
weekday = current_date.weekday()
if weekday >= 5: # sunday = 6
continue
if current_date in holidays:
continue
business_days_to_add -= 1
return current_date
#demo:
base["Target_date"]=date_by_adding_business_days(df["start_date"], 10, Holidays['Date_holi'])
但我收到此错误:
AttributeError:系列"对象没有属性工作日"
AttributeError: 'Series' object has no attribute 'weekday'
感谢您的帮助.
ALollz的评论非常有效;最好在创建过程中自定义日期以仅保留定义为您的问题的工作日.
The comments by ALollz are very valid; customizing your date during creation to only keep what is defined as business day for your problem would be optimal.
但是,我假设您无法预先定义工作日,并且需要使用按原样构造的数据框来解决问题.
However, I assume that you cannot define the business day beforehand and that you need to solve the problem with the data frame constructed as is.
这是一种可能的解决方案:
Here is one possible solution:
import pandas as pd
import numpy as np
from datetime import timedelta
# Goal is to offset a start date by N business days (weekday + not a holiday)
# Here we fake the dataset as it was not provided
num_row = 1000
df = pd.DataFrame()
df['start_date'] = pd.date_range(start='1/1/1979', periods=num_row, freq='D')
df['add_days'] = pd.Series([10]*num_row)
# Define what is a week day
week_day = [0,1,2,3,4] # Monday to Friday
# Define what is a holiday with month and day without year (you can add more)
holidays = ['10-30','12-24']
def add_days_to_business_day(df, week_day, holidays, increment=10):
'''
modify the dataframe to increment only the days that are part of a weekday
and not part of a pre-defined holiday
>>> add_days_to_business_day(df, [0,1,2,3,4], ['10-31','12-31'])
this will increment by 10 the days from Monday to Friday excluding Halloween and new year-eve
'''
# Increment everything that is in a business day
df.loc[df['start_date'].dt.dayofweek.isin(week_day),'target_date'] = df['start_date'] + timedelta(days=increment)
# Remove every increment done on a holiday
df.loc[df['start_date'].dt.strftime('%m-%d').isin(holidays), 'target_date'] = np.datetime64('NaT')
add_days_to_business_day(df, week_day, holidays)
df
要注意:我不使用"add_days"列,因为它只是重复的值.相反,我为函数 increment 使用了一个参数,该参数将增加 N 天数(默认值为N = 10).
To Note: I'm not using the 'add_days' column since its just a repeated value. I am instead using a parameter for my function increment which will increment by N number of days (with a default of N = 10).
希望有帮助!