Previous (business) dates pandas

与世无争的帅哥 提交于 2020-08-08 05:46:27

问题


I have a pandas.core.series.Series of specific dates (non-consecutive) which looks like the following:

0     1998-06-09
1     1998-08-07
2     1998-09-11
3     1998-10-13
4     1998-11-03
...   
231   2019-07-25
232   2019-09-12
233   2019-10-24

These dates are not necessarily business days. What I need is to create a list or series of dates which represent the previous day of the list that I have. In the new list, every previous day must be a business day, i.e. if (let's say) 1998-06-09 was a Monday, in the new list I should get 1998-06-05, i.e. the previous Friday. Any suggestions?


回答1:


pd.offsets.BusinessDay

When you consider a Business Day to be Monday - Friday

df['prev_bd'] = df['Date'] - pd.offsets.BusinessDay(n=1)
        Date    prev_bd
0 2012-12-20 2012-12-19
1 2012-12-21 2012-12-20
2 2012-12-22 2012-12-21
3 2012-12-23 2012-12-21
4 2012-12-24 2012-12-21
5 2012-12-25 2012-12-24
6 2012-12-26 2012-12-25
7 2012-12-27 2012-12-26
8 2012-12-28 2012-12-27
9 2012-12-29 2012-12-28

pd.offsets.CustomBusinessDay

When you also want to skip holidays (or any set of dates in particular). Here we exclude Federal Holidays, though you can skip whatever dates you want by providing the appropriate calendar.

from pandas.tseries.holiday import USFederalHolidayCalendar
df['prev_nohol'] = df['Date'] - pd.offsets.CustomBusinessDay(n=1, calendar=USFederalHolidayCalendar())
#PerformanceWarning

        Date    prev_bd prev_nohol
0 2012-12-20 2012-12-19 2012-12-19
1 2012-12-21 2012-12-20 2012-12-20
2 2012-12-22 2012-12-21 2012-12-21
3 2012-12-23 2012-12-21 2012-12-21
4 2012-12-24 2012-12-21 2012-12-21
5 2012-12-25 2012-12-24 2012-12-24
6 2012-12-26 2012-12-25 2012-12-24  # Christmas skipped because Federal Holiday
7 2012-12-27 2012-12-26 2012-12-26
8 2012-12-28 2012-12-27 2012-12-27
9 2012-12-29 2012-12-28 2012-12-28

Sample Data

import pandas as pd
df = pd.DataFrame({'Date': pd.date_range('2012-12-20', periods=10, freq='D')})


来源:https://stackoverflow.com/questions/60117208/previous-business-dates-pandas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!