gpt4 book ai didi

python - Pandas Holidays to Dataframe with Holiday Name

转载 作者:太空宇宙 更新时间:2023-11-04 00:31:29 24 4
gpt4 key购买 nike

到目前为止,这是我的代码:

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)

现在,我想要做的是将所有这些日期放入一个数据框中,其中假期名称作为一列,日期作为另一列。所以对于我的例子...

date           holiday
2012-01-01 New Years Day
2012-07-04 Fourth Of July
2012-11-22 Thanksgiving
....etc

最佳答案

我们可以使用cal.holidays(return_name=True)方法:

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

或您想要的格式:

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

关于python - Pandas Holidays to Dataframe with Holiday Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45682950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com