pandas :to_timedelta 与工作日 [英] pandas: to_timedelta with business days

查看:17
本文介绍了 pandas :to_timedelta 与工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to loop through a date range that has only business days in it, i.e. no weekends. To do that, I have the following command that basically picks every third Friday in a month and makes the column window equal to 2, 20 days from this third Friday. This code works totally fine.

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

command 指的是 20 天,包括周末,但我希望它指的是 20 WEEKDAYS;例如像这样:

command refers to 20 days INCLUDING weekends, but I want it to refer to 20 WEEKDAYS; e.g. something like this:

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

是否有一个简单的解决方法,以便我可以用其他东西替换D",或者我必须重写所有内容?

Is there an easy fix so that I can replace the "D" with something else or do I have to rewrite everything?

此外,我还想用不同的值标记第三个星期五附近的日子,例如third_friday 之后的 day +1 是 1,而 day+2 是 2.为此,我写了第二个 for 循环.这里是完整的例子:

Moreover, I also want to mark the days around the third Fridays with different values, e.g. day +1 after third_friday is 1 and day+2 is 2. To do that, I wrote a second for loop. Here the full example:

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]  

推荐答案

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

I believe you are looking for the BDay date off set

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

这篇关于 pandas :to_timedelta 与工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆