向pandas数据框中添加假日列。

4

我有一个pandas数据帧对象df,对应以下日期:

>> df.index

DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04',
               '2015-01-05', '2015-01-06', '2015-01-07', '2015-01-08',
               '2015-01-09', '2015-01-10'],
              dtype='datetime64[ns]', name='Date', length=10, freq=None)

我希望在df中添加一列,用于显示当前是否为公共假日:

import pandas as pd
import holidays

df['hols'] = holidays.CountryHoliday('AUS',prov='NSW').get(df.index.to_datetime())

我尝试运行代码并出现错误: AttributeError: 'DatetimeIndex' object has no attribute 'to_datetime'.

如果我尝试使用

df['hols'] = holidays.CountryHoliday('AUS',prov='NSW').get(pd.to_datetime(df.index))

我遇到了错误TypeError: 无法将类型 '<class 'pandas.core.indexes.datetimes.DatetimeIndex'>' 转换为日期。

我知道有一个名叫workalendar的软件包,可以从在Python中向数据框添加节假日列获得信息,但是我无法在我的大学电脑上安装该软件包。

1个回答

4

试试使用 lambda 函数的解决方案:

df['hols'] = pd.Series(df.index).apply(lambda x: holidays.CountryHoliday('AUS',prov='NSW').get(x)).values

get()方法应该只接收一个值,而不是整个索引或数组。当应用于您的数据时,结果如下:

                      hols
Date                      
2015-01-01  New Year's Day
2015-01-02            None
2015-01-03            None
2015-01-04            None
2015-01-05            None
2015-01-06            None
2015-01-07            None
2015-01-08            None
2015-01-09            None
2015-01-10            None

谢谢,看起来不错。有没有办法将这些值转换为 1(假期)和 0(非假期)? - Medulla Oblongata
1
是的,请尝试:df ['hols'] = df ['hols']。astype('bool')。astype('int') - ipj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接