我有一个 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)
Run Code Online (Sandbox Code Playgroud)
类似以下的工作,但是如果有人有一个更简单的解决方案,我将不胜感激。
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
Run Code Online (Sandbox Code Playgroud)
phi*_*686 10
您可以添加 0*BDay()
from pandas.tseries.offsets import BDay
df.index = df.index.map(lambda x : x + 0*BDay())
Run Code Online (Sandbox Code Playgroud)
如果有假期,您也可以将它与带有 CDay(calendar) 的假日日历一起使用。