我有一个 Python 中的 pandas DataFrame,其中两列表示开始日期和结束日期。 我想要:
- 给定两个 pandas 系列作为开始日期和结束日期作为输入...
- 对于每对开始结束日期,确定间隔 [start, end)(即包括开始但不包括结束)之间的任何日期是星期五还是星期六...
- 将 pandas Series 输出为 bool 值。
- 该解决方案应该相对较快,因为我处理的行数超过 200 万行。
数据集如下所示:
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))
关于python - 使用 Pandas 查找包含周末的日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46556542/