有效地比较 python 中两列中的每一对日期

Compare each pair of dates in two columns in python efficiently

我有一个数据框,其中包含一列开始日期和一列结束日期。我想通过确保开始日期早于结束日期(即 start_date < end_date)来检查日期的完整性。我有超过 14,000 个观察到 运行 到

我有以下形式的数据:

    Start       End
0   2008-10-01  2008-10-31  
1   2006-07-01  2006-12-31  
2   2000-05-01  2002-12-31  
3   1971-08-01  1973-12-31  
4   1969-01-01  1969-12-31  

我添加了一个列来写入结果,尽管我只是想突出显示是否有不正确的,以便我可以删除它们:

dates['Correct'] = " "

并开始使用以下方法检查每个日期对,其中我的数据框称为日期:

for index, row in dates.iterrows():
    if dates.Start[index] < dates.End[index]:
        dates.Correct[index] = "correct"
    elif dates.Start[index] == dates.End[index]:
        dates.Correct[index] = "same"
    elif dates.Start[index] > dates.End[index]:
        dates.Correct[index] = "incorrect"

有效,只是花费了非常非常长的时间(大约超过 15 分钟)。我需要更高效的 运行ning 代码 - 我做错了什么或可以改进吗?

由于不需要按顺序比较列表,您可以通过拆分数据集然后使用多个进程同时执行比较来提高性能。查看 multiprocessing 模块寻求帮助。

像下面这样的东西可能会更快:

import pandas as pd
import datetime

df = pd.DataFrame({
    'start': ["2008-10-01", "2006-07-01", "2000-05-01"],
    'end': ["2008-10-31", "2006-12-31", "2002-12-31"],
})


def comparison_check(df):
    start = datetime.datetime.strptime(df['start'], "%Y-%m-%d").date()
    end = datetime.datetime.strptime(df['end'], "%Y-%m-%d").date()
    if start < end:
        return "correct"
    elif start == end:
        return "same"
    return "incorrect"

In [23]: df.apply(comparison_check, axis=1)
Out[23]: 
0    correct
1    correct
2    correct
dtype: object

时间

In [26]: %timeit df.apply(comparison_check, axis=1)
1000 loops, best of 3: 447 µs per loop

所以根据我的计算,14,000 行应该需要 (447/3)*14,000 = (149 µs)*14,000 = 2.086s,所以可能少于 15 分钟:)

为什么不直接以矢量化的方式进行:

is_correct = dates['Start'] < dates['End']
is_incorrect = dates['Start'] > dates['End']
is_same = ~is_correct & ~is_incorrect