使用 Pandas 查找包含周末的日期范围

Find date ranges that include the weekend using Pandas

我在 Python 中有一个 pandas DataFrame,其中两列表示开始日期和结束日期。 我想:

数据集如下所示:

start       end
2013-08-02  2013-08-04
2014-11-24  2014-11-28
2013-10-29  2013-10-31
2013-12-06  2013-12-10
2014-08-15  2014-08-17

我会期待这样的事情:

has_weekend
TRUE
FALSE
FALSE
TRUE
TRUE

对于具有接近 2M 行的 DataFrame,我当前的方法非常慢。 这是代码:

df.apply(lambda x: np.any(np.in1d([d.weekday() for d in pd.date_range(x.start, x.end)],[4,5])), axis=1)

有什么想法吗?

解决方案 最快的解决方案是来自@Anton VBr

的修改后的答案
s = df.start.dt.dayofweek
e = df.end.dt.dayofweek
dt = (df.end- df.start).dt.days
has_weekend = ( ((s >= 4) & (s != 6)) | ( e>=5) | ((e < s) & (s != 6)) | (dt >= 6) )

我考虑了一些逻辑运算符,这些应该可以,但是它们在我测试的小集合上没有任何时间改进。

s = df.start.dt.dayofweek
e = df.end.dt.dayofweek
(((s >= 4) & (s != 6)) | (( e>=4) & (s != 6)) | (e < s))