熊猫:to_timedelta与工作日

时间:2017-05-31 15:11:02

标签: python pandas datetime timedelta

我想循环一个只有工作日的日期范围,即没有周末。 要做到这一点,我有以下命令基本上每个月的第三个星期五选择并使列窗口等于从第三个星期五起的2天,20天。这段代码完全正常。

for beg in pd.bdate_range("2000-01-01", "2017-05-01"):     
     beg= third_friday
     df["window"].loc[beg: beg + pd.to_timedelta(20,"D")] = 2
     if month==12:
         year=year+1
         month=0
     if year>=2017 and month>=3:
         break
     month = month +3
     monthcal = c.monthdatescalendar(year,month)
     third_friday = [day for week in monthcal for day in week if \
                day.weekday() == calendar.FRIDAY and \
               day.month == month][2]  

然而,

中的20
df["window"].loc[beg: beg + pd.to_timedelta(20,"D")] = 2

命令指的是包含周末的20天,但我希望它指的是20个周末;例如像这样的东西:

df["window"].loc[beg: beg + pd.to_timedelta(20, "Weekdays_only")] = 2

是否有一个简单的解决方案,以便我可以替换" D"与其他东西或我必须重写一切?

此外,我还想用不同的值来标记第三个星期五的日子,例如:在third_friday为1之后的第+1天和第2天为2.为此,我写了第二个for循环。这里有完整的例子:

for beg in pd.bdate_range("2000-01-01", "2017-05-01"):     
 beg= third_friday
 lower_counter = 0
 for j in range(0,-21,-1):    
   df["window_counter"].loc[beg - pd.to_timedelta(j,"D"):beg] = lower_counter       
   lower_counter = j         

 df["window"].loc[beg: beg + pd.to_timedelta(20,"D")] = 2
 if month==12:
     year=year+1
     month=0
 if year>=2017 and month>=3:
     break
 month = month +3
 monthcal = c.monthdatescalendar(year,month)
 third_friday = [day for week in monthcal for day in week if \
            day.weekday() == calendar.FRIDAY and \
           day.month == month][2]  

2 个答案:

答案 0 :(得分:3)

我相信您正在寻找BDay日期偏离集

import pandas as pd
from pandas.tseries.offsets import *

new_date = beg + BDay(20)

http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects

答案 1 :(得分:0)

20个工作日正好是28个日历日。

因此

df["window"].loc[beg: beg + pd.to_timedelta(28,"D")] = 2

应该工作