Reputation: 89
Wonking on pandas dataframes -
I have a date format like this: datetime64[ns]
and a column with a int64
format.
the dataframe looks like this:
date days
0 2019-07-04 1
1 2019-10-17 1
2 2019-10-17 2
i want to use this function to add n business days:
def add_business_days(from_date,ndays):
business_days_to_add = abs(ndays)
current_date = from_date
sign = ndays/abs(ndays)
while business_days_to_add > 0:
current_date += datetime.timedelta(sign * 1)
weekday = current_date.weekday()
if weekday >= 5: # sunday = 6
continue
business_days_to_add -= 1
return current_date
But i somehow get this error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Could you help on that ?
Upvotes: 1
Views: 2043
Reputation: 5774
pandas
has an implemented support for business days. I am not absolutely sure what your output is supposed to like like (since you did not include an expected output, could you please add it?), but I guess this is what you want:
pd.to_datetime(from_date) + pd.offsets.BDay(ndays)
Assuming your dataframe looks like this:
dates = [pd.to_datetime('2019-07-04'), pd.to_datetime('2019-10-17'), pd.to_datetime('2019-10-17')]
df = pd.DataFrame(data={'date': dates, 'days': [1, 1, 2]})
The conversion to a timestamp with pd.to_datetime()
can be omitted.
Upvotes: 2
Reputation: 862661
Use lambda function with offsets.BDay
:
def add_business_days(from_date,ndays):
return from_date + pd.offsets.BDay(ndays)
df['date'] = pd.to_datetime(df['date'])
df['new'] = df.apply(lambda x: add_business_days(x['date'], x['days']), axis=1)
Or:
df['new'] = df.apply(lambda x: x['date'] + pd.offsets.BDay(x['days']), axis=1)
print (df)
date days new
0 2019-07-04 1 2019-07-05
1 2019-10-17 1 2019-10-18
2 2019-10-17 2 2019-10-21
Upvotes: 1