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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32834946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:56:42  来源:igfitidea点击:

Pandas offset DatetimeIndex to next business if date is not a business day

pythonpandas

提问by mgilbert

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.

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

Some example data would be

一些示例数据是

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

回答by phil_20686

You can add 0*BDay()

您可以添加 0*BDay()

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

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

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

回答by matt_s

You can map the index with a lambda function, and set the result back to the index.

您可以使用 lambda 函数映射索引,并将结果设置回索引。

df.index = df.index.map(lambda x: x if x.dayofweek < 5 else x + pd.DateOffset(7-x.dayofweek))

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