熊猫为营业日DateRange操纵频率

时间:2019-11-27 18:46:20

标签: python pandas

我正在尝试将一组与日期相关的常见日期列添加到我的数据框中,而构建这些日期列的方法不在.date_range() pandas方法中,该方法将具有我的数据框的日期范围。

虽然我可以将.index.day.index.weekday_name之类的方法用于常规日期列,但我想根据我构造的date_range设置工作日列,但不确定是否可以使用{{ 1}}属性昵称freq,或者是否需要创建新的日期范围。

此外,我希望不要根据我的假期日期列表来计算那些工作日。

这是我的设置:

假期表

'B'

基本日期表

holiday_table = holiday_table.set_index('date')
holiday_table_dates = holiday_table.index.to_list() # ['2019-12-31', etc..]

data_date_range = pd.date_range(start=date_range_start, end=date_range_end) df = pd.DataFrame({'date': data_date_range}).set_index('date') df['day_index'] = df.index.day # Weekday Name df['weekday_name'] = df.index.weekday_name # Business day df['business_day'] = data_date_range.freq("B") 处的错误:

df['business_day'] = data_date_range.freq("B")

1 个答案:

答案 0 :(得分:2)

好的,我想我现在已经明白你的问题了。您正在寻找一个新的工作日列(不包括自定义假期)。在我的示例中,我只是使用了来自熊猫的美国常规假期,但是您已经在holiday_table_dates中将假期作为列表,但是您仍然可以按照我的示例的一般布局进行特定使用。我还假设您可以在business_day列中使用布尔值:

import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar as h_cal

# sample data
data_date_range = pd.date_range(start='1/1/2019', end='12/31/2019')
df = pd.DataFrame({'date': data_date_range}).set_index('date')
df['day_index'] = df.index.day
# Weekday Name
df['weekday_name'] = df.index.weekday_name

# this is just a sample using US holidays
hday = h_cal().holidays(df.index.min(), df.index.max())
# b is the same date range as bove just with the freq set to business days
b = pd.date_range(start='1/1/2019', end='12/31/2019', freq='B')
# find all the working business day where b is not a holiday
bday = b[~b.isin(hday)]
# create a boolean col where the date index is in your custom business day we just created
df['bday'] = df.index.isin(bday)


            day_index weekday_name   bday
date                                     
2019-01-01          1      Tuesday  False
2019-01-02          2    Wednesday   True
2019-01-03          3     Thursday   True
2019-01-04          4       Friday   True
2019-01-05          5     Saturday  False