pandas :创建日期范围 [英] Pandas: Date range creation

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

问题描述

我想在Pandas中创建一个考虑工作日的每月日期范围.

I'd like to create a monthly date range within Pandas taking in consideration of business days.

例如: dt_range = pd.date_range(start ='2017-12-20',period = 5,freq ='M')

含义:从2017年12月20日开始,每20日滚动一次,为期5个月,如果该滚动日期不是工作日,则采用下一个滚动日期(但保留20日以进行下一次观察).

Meaning: starting on 2017-12-20, roll on every 20th for 5 months, if such roll date is not a business day, take the following roll date (but keep the 20th for next observation).

与之类似:以日期结尾,向后滚动,每20天一次,持续5个月.例如:

Likewise: ending on a date, roll backwards, each 20th for 5 months. such as:

dt_range = pd.date_range(end ='2018-05-20',period = 5,freq ='M')

我一直在咨询熊猫偏移别名但是,由于他们专注于月末,月初,所以我的思维方式似乎与他们不同步,而且我找不到简单的月度记录.这有点信息超载,我相信这是一种简单的方法,因此,我想寻求一些帮助/指导以找到答案.

I have been consulting Pandas offset aliases however, it seems my way of thinking does not sync with theirs, as they are focused on month end, month start and I cannot find a simple monthly roll. It is a bit of information overload, and I am sure it exist an easy way, and therefore I would like to ask for some help/guidance to find the answer.

推荐答案

一种解决方法:

dt_range = pd.date_range(start='2017-12-20', periods=5, freq='MS') + pd.DateOffset(days=18) + pd.tseries.offsets.BusinessDay(1)

输出:

DatetimeIndex(['2018-01-22', '2018-02-20', '2018-03-20', '2018-04-20',
               '2018-05-21'],
              dtype='datetime64[ns]', freq=None)

我只是使用 date_range(..,freq ='MS)进入月份的第一天,然后我将18天加到第19天.然后,如中所述,使用 offsets.BusinessDay 这样的帖子以查找下一个工作日.

I just go to the first day of the month with the date_range(.., freq='MS) and then I add 18 days to get to 19th day. Then I use offsets.BusinessDay as described in this SO post to find the next business day.

如果要包括开始日期,则必须提前一个月开始.这种行为有些奇怪,但是很容易解决.

If you want to include your start day, you have to start one month earlier. This behavior is somewhat peculiar, but easy to account for.

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

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