Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Holidays to Dataframe with Holiday Name

This is my code so far:

year = 2012
start = datetime.date(year, 1, 1)
end = start + pd.offsets.MonthEnd(72)

class FrBusinessCalendar(AbstractHolidayCalendar):
""" Custom Holiday calendar 
"""
rules = [
    Holiday('New Years Day', month=1, day=1),
    #USThanksgivingDay,
    Holiday('Fourth Of July', month=7, day=4),
    Holiday('Thanksgiving', month=11, day=1, offset=DateOffset(weekday=TH(4))),
    Holiday('Black Friday', month=11, day=1, offset=pd.DateOffset(weekday=FR(4))),
    Holiday("Cyber Monday", month=11, day=1, offset=[pd.DateOffset(weekday=SA(4)), pd.DateOffset(2)]),
    Holiday('Christmas Day', month=12, day=25)
]

cal = FrBusinessCalendar()
# Getting the holidays (off-days) between two dates
cal.holidays(start=start, end=end)

Now, what I want to do is get all these dates into a dataframe with the name of the holiday as one column and the date as the other column. So for my example...

date           holiday
2012-01-01     New Years Day
2012-07-04     Fourth Of July
2012-11-22     Thanksgiving
....etc
like image 548
Hound Avatar asked Mar 09 '23 08:03

Hound


1 Answers

we can use cal.holidays(return_name=True) method:

In [85]: holidays = cal.holidays(start=start, end=end, return_name=True)

In [86]: pd.options.display.max_rows = 20

In [87]: holidays
Out[87]:
2012-01-01     New Years Day
2012-07-04    Fourth Of July
2012-11-22      Thanksgiving
2012-11-23      Black Friday
2012-11-26      Cyber Monday
2012-12-25     Christmas Day
2013-01-01     New Years Day
2013-07-04    Fourth Of July
2013-11-22      Black Friday
2013-11-25      Cyber Monday
                   ...
2016-11-24      Thanksgiving
2016-11-25      Black Friday
2016-11-28      Cyber Monday
2016-12-25     Christmas Day
2017-01-01     New Years Day
2017-07-04    Fourth Of July
2017-11-23      Thanksgiving
2017-11-24      Black Friday
2017-11-27      Cyber Monday
2017-12-25     Christmas Day
Length: 36, dtype: object

or in your desired format:

In [88]: holidays.reset_index(name='holiday').rename(columns={'index':'date'})
Out[88]:
         date         holiday
0  2012-01-01   New Years Day
1  2012-07-04  Fourth Of July
2  2012-11-22    Thanksgiving
3  2012-11-23    Black Friday
4  2012-11-26    Cyber Monday
5  2012-12-25   Christmas Day
6  2013-01-01   New Years Day
7  2013-07-04  Fourth Of July
8  2013-11-22    Black Friday
9  2013-11-25    Cyber Monday
..        ...             ...
26 2016-11-24    Thanksgiving
27 2016-11-25    Black Friday
28 2016-11-28    Cyber Monday
29 2016-12-25   Christmas Day
30 2017-01-01   New Years Day
31 2017-07-04  Fourth Of July
32 2017-11-23    Thanksgiving
33 2017-11-24    Black Friday
34 2017-11-27    Cyber Monday
35 2017-12-25   Christmas Day
like image 112
MaxU - stop WAR against UA Avatar answered Mar 20 '23 15:03

MaxU - stop WAR against UA