1

I have the below dataframe

df = pd.DataFrame({'Start_Date': ['2018-08-23', '2018-08-16', '2018-08-24', '2018-08-29'], 'Days': ['3', '1', '3', '0']})

I would like to create a new column "End_Date". End_Date will be Start_Date + Days. also, End_Date should be only weekdays (exclude weekend).

Expected out

Start Date      Days   End_Date
2018-08-23      3      2018-08-28    
2018-08-16      1      2018-08-17
2018-08-24      3      2018-08-29
2018-08-29      0      2018-08-29

I have tried to use the solution from omz but it is not working for me. I have tried using workday function but this is also not working.

Any idea?

Joe
  • 12,057
  • 5
  • 39
  • 55
Hakumaru
  • 55
  • 5

2 Answers2

0

You can use BDay in this way:

from pandas.tseries.offsets import BDay

df['Start_Date'] = pd.to_datetime(df['Start_Date'])
df['End_Date']  = df.apply(lambda x: x['Start_Date'] + BDay(x['Days']), axis=1)

Output:

   Days Start_Date   End_Date
0     3 2018-08-23 2018-08-28
1     1 2018-08-16 2018-08-17
2     3 2018-08-24 2018-08-29
3     0 2018-08-29 2018-08-29
Joe
  • 12,057
  • 5
  • 39
  • 55
  • Thank you...this give me the exact results I need. – Hakumaru Nov 27 '18 at 08:13
  • How could I improve it if i would like to have holidays excluded as well? – Hakumaru Nov 28 '18 at 02:07
  • For the holidays it is a bit more complicated because from countries to countries they are different. If is the `USFederalHolidayCalendar` you can take a look to tihs answer: https://stackoverflow.com/questions/44822697/business-days-between-two-dates-excluding-holidays-in-python or if it is just for a couple of years you can set your holidays yourself: https://stackoverflow.com/questions/44828008/adding-holidays-to-usfederalholidaycalendar – Joe Nov 28 '18 at 07:10
  • Can you post the df in a new questions? – Joe Nov 29 '18 at 07:35
0

You can use numpy.busday_offset to get the next business day.

In [1]: import numpy as np

In [2]: df['End_Date'] = df.apply(lambda x: np.busday_offset(x[0], x[1]), axis=1)

In [3]: df
Out[3]:
   Start_Date Days   End_Date
0  2018-08-23    3 2018-08-28
1  2018-08-16    1 2018-08-17
2  2018-08-24    3 2018-08-29
3  2018-08-29    0 2018-08-29
Praveen
  • 8,945
  • 4
  • 31
  • 49