【问题标题】:Pandas check for overlapping dates in multiple rowsPandas 检查多行中的重叠日期
【发布时间】:2016-04-15 18:14:58
【问题描述】:

我需要在一个大的groupby 查询上运行一个函数来检查两个子组是否有任何重叠的日期。以下是单个群组tmp的示例:

    ID  num start       stop        subGroup
0   21  10  2006-10-10  2008-10-03  1
1   21  46  2006-10-10  2100-01-01  2
2   21  5   1997-11-25  1998-09-29  1
3   21  42  1998-09-29  2100-01-01  2
4   21  3   1997-01-07  1997-11-25  1
5   21  6   2006-10-10  2008-10-03  1
6   21  47  1998-09-29  2006-10-10  2
7   21  4   1997-01-07  1998-09-29  1

我为此编写的函数如下所示:

def hasOverlap(tmp):
    d2_starts = tmp[tmp['subGroup']==2]['start']
    d2_stops = tmp[tmp['subGroup']==2]['stop']
    return tmp[tmp['subGroup']==1].apply(lambda row_d1:
         (
            #Check for part nested D2 in D1
            ((d2_starts >= row_d1['start']) &
             (d2_starts < row_d1['stop']) ) |
            ((d2_stops >= row_d1['start']) &
             (d2_stops < row_d1['stop']) ) |
            #Check for fully nested D1 in D2
            ((d2_stops >= row_d1['stop']) &
             (d2_starts <= row_d1['start']) )
         ).any()
         ,axis = 1
        ).any()

问题是这段代码有很多冗余,当我运行查询时:

groups.agg(hasOverlap)

终止需要非常长的时间。

是否有任何性能修复(例如使用内置函数或 set_index)可以加快速度?

【问题讨论】:

  • 您是在比较字符串还是日期时间对象:D?
  • 将 datetime 转换为 unix 时间戳,减去 min,然后 .astype(np.int32) 可能有帮助吗?
  • 另外,你做了两次.any()。看起来如果任何比较给出了真正的输出,你就可以跳出来。只有两个 for 循环可能会快得多。

标签: python performance pandas


【解决方案1】:

您只是想根据重叠的存在返回“True”还是“False”?如果是这样,我只需获取每个子组的日期列表,然后使用 pandas isin 方法检查它们是否重叠。

你可以试试这样的:

#split subgroups into separate DF's
group1 = groups[groups.subgroup==1]
group2 = groups[groups.subgroup==2]

#check if any of the start dates from group 2 are in group 1
if len(group1[group1.start.isin(list(group2.start))]) >0:
    print "Group1 overlaps group2"

#check if any of the start dates from group 1 are in group 2
if len(group2[group2.start.isin(list(group1.start))]) >0:
    print "Group2 overlaps group1"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 2015-04-24
    • 2011-02-02
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多