首页 > 解决方案 > 有没有更好的方法在 Pandas/Python 中实现匹配算法?

问题描述

我有两个(假设是旅行者)出发和到达巴士站的数据集。我有他们到达时间、离开时间和其他一些关于他们旅行特征(公司名称等)的数据,如下所示:

到达

ID, ArrivalTime, CompanyName
1, 10:30, 'EuroBus'
2, 10:30, 'EuroBus'
3, 10:40, 'OverflowTrip'

出港

ID, DepartureTime, CompanyName
1, 13:30, 'EuroBus'
2, 13:40,' OverflowTrip'
3, 12:10, 'OverflowTrip'

我需要或多或少地像这样匹配它们:

for each arrivalPassanger in Arrivals
    possible_Departures <- select_possible_departures( Departures, matching_criteria )
    selected_Departure <- select_departure( Departures, more_specific_matching_criteria )
    arrivalPassanger.departure <- selected_Departure
    Departures.remove( selected_Departure )

因为我已经在使用 Pandas,所以我的第一种方法是

    for arrivalPassanger in Arrivals.itertuples():
        #This criteria is going to be more complex
        possible_Departures = Departures[Departures.Time >= (arrivalPassanger .ArrivalTime + MARGIN)]

        if possible_Departures.shape[0] == 0:
            Arrivals.loc[arrivalPassanger .Index, "ID_Departure"] = "Unmatched"
        else:
            #This criteria is going to be more complex, for now i take the first occurrence
            selected_Departure = Departures.iloc[0]
            Arrivals.loc[arrivalPassanger.Index, "ID_Departure"] = selected_Departure.ID
            Departures.drop(selected_Departure.name, inplace=True)

现在它可以工作,并且由于数据集没有那么大(每个大约 20k),它们不会花费太多时间,但是虽然我计划增加匹配标准的复杂性,并且我看到数据集会更大. 我应该采取不同的方法吗?Pandas 有更好的方法来做到这一点吗?我应该改用 numpy 数组吗?我知道在 Pandas 中迭代不是推荐的选项。

PS:我不确定“匹配算法”在英文中是否是一个好名字......

周末愉快 =)

标签: pythonpandasalgorithmsimulation

解决方案


推荐阅读