如何在python中检查时间段中是否包含假日

2024-04-19 17:33:10 发布

您现在位置:Python中文网/ 问答频道 /正文

pandas dataframe中有两列,开始日期和结束日期。在

我想知道每一行的时间段中是否包括假日。在

我想创建一个新列来显示是或否

id  Start Date  End Date
0   2019-09-27  2019-10-06
1   2019-10-09  2019-10-22
2   2019-05-04  2019-05-15
3   2019-09-18  2019-09-29

我知道如何检查某个特定的日期是否是假日

但是我如何检查每一行的持续时间呢?在

^{pr2}$

我希望还有另一个布尔列要检查 如果每行(id)包含开始日期和结束日期之间的任何假日

id  Start Date  End Date    Holiday
0   2019-09-27  2019-10-06  True
1   2019-10-09  2019-10-22  False
2   2019-05-04  2019-05-15  True
3   2019-09-18  2019-09-29  False

Tags: idfalsetruedataframepandasdatestartend
2条回答

对数据帧的每一行应用检查函数:

df['Holiday'] = df.apply(lambda x:\
                   calendar().holidays(start=x['Start Date'],
                                       end=x['End Date']).size, axis=1)\
  .astype(bool) # Convert the answer to a boolean
#0    False
#1     True
#2    False
#3    False

我要做什么

#holidays = calendar().holidays(start = df['Start Date'].min(), end = df['End Date'].max())
l=[any(x<=z and y>=z for z in holidays.tolist()) for x , y in zip(df['Start Date'],df['End Date'])]
[False, True, False, False]
df['Holiday']=l

同时检查When should I ever want to use pandas apply() in my code?

相关问题 更多 >