python - Pandas 操纵工作日日期范围的频率

标签 python pandas

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

虽然我可以对一般日期列使用 .index.day.index.weekday_name 等方法,但我想根据 date_range 设置工作日列已构造,但不确定是否可以使用 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") 处出现错误:

---> 13 df['business_day'] = data_date_range.freq("B")
ApplyTypeError: Unhandled type: str

最佳答案

好的,我想我现在明白你的问题了。您希望创建一个新的工作日列(不包括您的自定义假期)。在我的示例中,我只使用了 pandas 中的美国常规假期,但您已经将假期作为 holiday_table_dates 中的列表,但您仍然应该能够遵循我的示例的总体布局以供您特定使用。我还假设您可以接受 business_day 列的 bool 值:

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

关于python - Pandas 操纵工作日日期范围的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076696/

相关文章:

python - 如何获取子类的文件名?

python - Peewee - 如何执行原始查询并将其映射到字典?

python - 如何在 pandas 数据帧行中检测到第一个非 nan 值后找到前 5 个值(包括 nan)?

python - 带有公差参数的 Pandas merge_asof 失败

python - 排除匹配模式中的一列

python - 错误 : [Errno -2] Name or service not known

python - 如何从模型字段中获取 Django 表单字段?

python - NSP 中最小化的绝对差

python - Pandas - 提取行直到满足条件

python - 如何使用 .loc 在 for 循环中将数据帧行追加到另一个数据帧行?