如果日期不是工作日,熊猫会将DatetimeIndex偏移到下一个业务


问题内容

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

一些示例数据将是

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)

类似于以下内容的作品,但是如果有人提出的解决方案更简单一点,我将不胜感激。

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()

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

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