以前(营业)的日期 pandas [英] Previous (business) dates pandas
问题描述
我有一个特定日期(非连续)的 pandas.core.series.Series
,它类似于以下内容:
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
这些日期不一定是工作日。我需要创建一个列表或一系列日期来表示我拥有的列表的前一天。在新列表中,每个前一天必须是一个工作日,即(假设)1998-06-09是星期一,在新列表中,我应该得到1998-06-05,即前一个星期五。有建议吗?
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?
推荐答案
pd.offsets.BusinessDay
当您认为工作日为星期一-星期五
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
当您还想跳过假期(或特别是任何日期集)时)。这里我们不包括联邦假日,尽管您可以通过提供适当的日历来跳过任何日期。
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
样本数据
import pandas as pd
df = pd.DataFrame({'Date': pd.date_range('2012-12-20', periods=10, freq='D')})
这篇关于以前(营业)的日期 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!