我想遍歷只有工作日的日期範圍,即沒有周末。 要做到這一點,我有以下命令,基本上每月選擇第三個星期五,並使列窗口從第三個星期五開始等於2,20天。這段代碼工作得很好。pandas:to_timedelta和工作日
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]
然而,在
df["window"].loc[beg: beg + pd.to_timedelta(20,"D")] = 2
命令20指的是20天,包括週末,但我想它來指20個WEEKDAYS;例如是這樣的:
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]
看一看這個[SO後(https://stackoverflow.com/questions/31588148/adding-business-days-to-datetime-column ) –