Python中是否有一种方法可以在熊猫时间序列中标记中国的假期

问题描述 投票:0回答:1

[我想在我的时间序列中的日期(来自中国的数据)的额外一栏中将其标记为holiday(布尔值true)和非holiday(布尔值false)。

我是这个主题的新手,目前我正试图找出解决这个问题的方法。

我有以下几天要在2020年作为中国的法定假日:

Chinese Holidays 2020

据我所知,中国没有开箱即用的日历,所以我将必须创建一个自定义日历,如下所示:

from pandas.tseries.holiday import Holiday,AbstractHolidayCalendar
    class ChineseHolidays(AbstractHolidayCalendar):
    rules = [Holiday('Chinese New Year', month=1, day=25),
             'Question: How to add more than one day?',
             etc,
            ...]

    cal = ChineseHolidays()

下一步将创建“假期”列,如下所示:

holidays = cal.holidays(start=X['timestamp'].min(), end = X['timestamp'].max())

X.assign(Holidays=X['timestamp'].isin(cal.holidays()).astype(int))

我的问题是:

1)这通常是适当的方法吗?

2)如何在Holiday('农历新年',month = 1,day = 25)行中定义从1月24日开始到1月30日结束的日子?有没有一种方法可以定义休假,而不是只定义一天?

感谢您的帮助。

最佳,

B。

python pandas time-series python-holidays
1个回答
0
投票

目前,我执行了以下操作:

```
 import holidays
 chinese_holidays = holidays.HolidayBase() 
 chinese_holidays.append({'01-01-2019':'New Years Day 2019'},
               {'04-02-2019':'Chinese New Year 2019'},
               {'05-02-2019':'Chinese New Year 2019'},
               {'06-02-2019':'Chinese New Year 2019'},
               {'07-02-2019':'Chinese New Year 2019'},
               {'08-02-2019':'Chinese New Year 2019'},
               {'09-02-2019':'Chinese New Year 2019'},
               {'10-02-2019':'Chinese New Year 2019'},
               {'05-04-2019':'Ching Ming Festival 2019'},
               {'01-05-2019':'Labours Day 2019'},
               {'02-05-2019':'Labours Day 2019'},
               {'03-05-2019':'Labours Day 2019'},
               {'13-09-2019':'Mid Autumn Festival 2019'},
               {'01-10-2019':'National Day 2019'},
               {'02-10-2019':'National Day 2019'},
               {'03-10-2019':'National Day 2019'},
               {'04-10-2019':'National Day 2019'},
               {'07-10-2019':'National Day 2019'},
               {'01-01-2020':'New Years Day 2020'},
               {'24-01-2020':'Chinese New Year 2020'},
               {'25-01-2020':'Chinese New Year 2020'},
               {'26-01-2020':'Chinese New Year 2020'},
               {'27-01-2020':'Chinese New Year 2020'},
               {'28-01-2020':'Chinese New Year 2020'},
               {'29-01-2020':'Chinese New Year 2020'},
               {'30-01-2020':'Chinese New Year 2020'}
              ) 
```

现在,如果我想检查天气或索引栏中是否有一天是假期,我可以执行以下操作,并得到该行的结果:

print(y.index[1] in chinese_holidays)

但是如果我申请:

print(y.index in chinese_holidays)

我收到此错误消息:

TypeError: Cannot convert type '<class 'pandas.core.indexes.datetimes.DatetimeIndex'>' to date.

任何想法为什么以及如何解决这个问题?

最佳

© www.soinside.com 2019 - 2024. All rights reserved.