如果日期不是工作日, pandas 会将DatetimeIndex偏移到下一个业务 [英] Pandas offset DatetimeIndex to next business if date is not a business day

查看:66
本文介绍了如果日期不是工作日, pandas 会将DatetimeIndex偏移到下一个业务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame,该索引与该月的最后一天建立索引.有时这个日期是工作日,有时是周末.忽略假期,如果日期在周末,我希望将日期偏移到下一个营业日,如果已经在工作日,则将结果保持不变.

I have a DataFrame which is indexed with the last day of the month. Sometimes this date is a weekday and sometimes it is a weekend. Ignoring holidays, I'm looking to offset the date to the next business date if the date is on a weekend and leave the result unchanged if it is already on a weekday.

某些示例数据应该是

import pandas as pd
idx = [pd.to_datetime('20150430'), pd.to_datetime('20150531'), 
       pd.to_datetime('20150630')]
df = pd.DataFrame(0, index=idx, columns=['A'])
df

            A
2015-04-30  0
2015-05-31  0
2015-06-30  0

df.index.weekday
array([3, 6, 1], dtype=int32)

类似下面的作品,但是如果有人有一个更简单的解决方案,我将不胜感激.

Something like the following works, however I would appreciate if someone has a solution that is a little more straightforward.

idx = df.index.copy()
wknds = (idx.weekday == 5) | (idx.weekday == 6)
idx2 = idx[~wknds]
idx2 = idx2.append(idx[wknds] + pd.datetools.BDay(1))
idx2 = idx2.order()
df.index = idx2
df

            A
2015-04-30  0
2015-06-01  0
2015-06-30  0

推荐答案

您可以添加0 * BDay()

You can add 0*BDay()

from pandas.tseries.offsets import BDay
df.index = df.index.map(lambda x : x + 0*BDay())

如果有假期,您也可以将其与带有CDay(calendar)的假期日历一起使用.

You can also use this with a Holiday calendar with CDay(calendar) in case there are holidays.

这篇关于如果日期不是工作日, pandas 会将DatetimeIndex偏移到下一个业务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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