gpt4 book ai didi

python - 识别数据框中重叠时间跨度的数量

转载 作者:太空宇宙 更新时间:2023-11-03 11:27:59 24 4
gpt4 key购买 nike

我有一个包含开始日期和结束日期的契约(Contract)列表。

如何计算契约(Contract)生命周期内重叠契约(Contract)的数量?

df = pd.DataFrame({
'contract': pd.Series(['A1', 'A2', 'A3', 'A4']),
'start': pd.Series(['01/01/2015', '03/02/2015', '15/01/2015', '10/01/2015']),
'end': pd.Series(['16/01/2015', '10/02/2015', '18/01/2015', '12/01/2015'])
})

给出:

  contract         end       start
0 A1 16/01/2015 01/01/2015
1 A2 10/02/2015 03/02/2015
2 A3 18/01/2015 15/01/2015
3 A4 12/01/2015 10/01/2015

A1 与 A3 和 A4 重叠,因此重叠 = 2。A2 没有契约(Contract)重叠,因此重叠 = 0。A3 与 A1 重叠,因此重叠 = 1。A4 与 A1 重叠,因此重叠 = 1。

我可以只比较每个时间跨度(从开始到结束),但那是 O(n**2)有更好的主意吗?

我觉得可以通过排序然后 looping through the sorted ranges 来获得改进

最佳答案

这里有一个方法:

df = pd.DataFrame({
'contract': pd.Series(['A1', 'A2', 'A3', 'A4']),
'start': pd.Series(['01/01/2015', '03/02/2015', '15/01/2015', '10/01/2015']),
'end': pd.Series(['16/01/2015', '10/02/2015', '18/01/2015', '12/01/2015'])
})
df['start'] = pd.to_datetime(df.start, dayfirst=True)
df['end'] = pd.to_datetime(df.end, dayfirst=True)

periods = df[['start', 'end']].apply(lambda x: (pd.date_range(x['start'], x['end']),), axis=1)
overlap = periods.apply(lambda col: periods.apply(lambda col_: col[0].isin(col_[0]).any()))
df['overlap_count'] = overlap[overlap].apply(lambda x: x.count() - 1, axis=1)
print df

产生:

  contract        end      start  overlap_count
0 A1 2015-01-16 2015-01-01 2
1 A2 2015-02-10 2015-02-03 0
2 A3 2015-01-18 2015-01-15 1
3 A4 2015-01-12 2015-01-10 1

我更新了代码以输出重叠次数而不是重叠天数。

关于python - 识别数据框中重叠时间跨度的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30032723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com