1

I am trying to do a simple operation:

  1. Get the date of one month ago
  2. If the result is not business day, then take next business day.

using code:

from pandas.tseries.offsets import DateOffset, BDay
from datetime import datetime

def last_month(d):
    start = time.time()
    last = d - DateOffset(months=1) + BDay(0)
    end = time.time()
    print (end - start)

now = datetime.now()
last_month(now)

I get the time printed as 0.000224113464355

I think for my requirement it is too slow. I have about 100K dates that I need to do similar operation like above last_month, then the total cost will be 0.000224113464355 * 100, 000 about 22 seconds.

Is there any better way in python or pandas to achieve this faster?

3
  • Doesn't it just work if you just did df['date_col'] - DateOffset(months=1) + BDay(0)?
    – EdChum
    Feb 3, 2016 at 12:58
  • I get 10 loops, best of 3: 72.4 ms per loop for 100K rows
    – EdChum
    Feb 3, 2016 at 13:07
  • @EdChum I can't do it because I am not transforming the date index of the df. Instead, for each date, I need to find data of 12 business days from 12 months, which means say for 2016-2-2, i need to find 2016-01-02, 2015-12-02, etc, if not weekday, then find the nearest bday. Feb 4, 2016 at 7:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.