Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Business days to datetime column

I need to add business days to the dates listed in an existing column in a dataframe. The data in the column is in the datetime64[ns] type. Using the suggestions from Business days in Python, I tried the code listed below.

import datetime
from pandas.tseries.offsets import BDay

df['Math Admin Date'] + BDay(1)

I got the following error message:

TypeError: cannot use a non-absolute DateOffset in datetime/timedelta operations [<BusinessDay>]

How can I add business days to my datetime column?

like image 623
BGreen Avatar asked Jul 23 '15 13:07

BGreen


2 Answers

Unfortunately offsets don't support operations using array like objects so you have to apply the offset for each element:

In [208]:
import datetime as dt
from pandas.tseries.offsets import BDay
​
df = pd.DataFrame({'Math Admin Date':pd.date_range(start=dt.datetime(2015,6,1), end = dt.datetime(2015,6,30))})
df['Math Admin Date'].apply(lambda x: x + BDay(1))

Out[208]:
0    2015-06-02
1    2015-06-03
2    2015-06-04
3    2015-06-05
4    2015-06-08
5    2015-06-08
6    2015-06-08
7    2015-06-09
8    2015-06-10
9    2015-06-11
10   2015-06-12
11   2015-06-15
12   2015-06-15
13   2015-06-15
14   2015-06-16
15   2015-06-17
16   2015-06-18
17   2015-06-19
18   2015-06-22
19   2015-06-22
20   2015-06-22
21   2015-06-23
22   2015-06-24
23   2015-06-25
24   2015-06-26
25   2015-06-29
26   2015-06-29
27   2015-06-29
28   2015-06-30
29   2015-07-01
Name: Math Admin Date, dtype: datetime64[ns]

Using a Timedelta would work but this doesn't support business days at the moment:

df['Math Admin Date'] + pd.Timedelta(1,'D')
like image 160
EdChum Avatar answered Nov 05 '22 21:11

EdChum


For versions:

In [1140]: pd.__version__
Out[1140]: '1.1.0'

No need of using apply which is loops under the hood. You can simply do:

In [1138]: df['Math Admin Date'] = df['Math Admin Date'] + BDay(1)

In [1139]: df
Out[1139]: 
   Math Admin Date
0       2015-06-02
1       2015-06-03
2       2015-06-04
3       2015-06-05
4       2015-06-08
5       2015-06-08
6       2015-06-08
7       2015-06-09
8       2015-06-10
9       2015-06-11
10      2015-06-12
11      2015-06-15
12      2015-06-15
13      2015-06-15
14      2015-06-16
15      2015-06-17
16      2015-06-18
17      2015-06-19
18      2015-06-22
19      2015-06-22
20      2015-06-22
21      2015-06-23
22      2015-06-24
23      2015-06-25
24      2015-06-26
25      2015-06-29
26      2015-06-29
27      2015-06-29
28      2015-06-30
29      2015-07-01
like image 37
Mayank Porwal Avatar answered Nov 05 '22 21:11

Mayank Porwal