首页 > 解决方案 > 在Python中的值范围内根据多个条件匹配两个数据框

问题描述

我需要一些关于如何在 Python 中根据多个标准匹配两个数据帧的提示/线索,其中一些标准正在寻找范围内的值。这个例子:

1.第一个数据框是一个合同,我们的位置从国家,从邮政编码低,从邮政编码高,到国家,到邮政编码低,到邮政编码高,合同ID。

from country from postal code low from postal code high to country to postal code low to postal code high ID
SE         0         19999            DE      90000         99999   ID1
SE     20000         29999            DE      90000         99999   ID2
SE     30000         39999            DE      90000         99999   ID3
SE     40000         49999            DE      90000         99999   ID4
SE     41250         41250            DE      90000         99999   ID5

2.Second 数据框是具有准确邮政编码的统计文件,我需要从第一个数据库中找到所有唯一匹配项:

From country  from postal code    to country  To postal code   ID (that should be the result):
SE              21789              DE          91000            ID2
SE              41250              DE          91000            ID4, ID5

在 excel 中可以通过索引和匹配以及数组函数来完成,因为两个数据帧都涉及数万甚至数十万行,在 excel 中这样做并不是最佳选择,所以寻找 Python 解决方案。我是 Python 的初学者,所以至少知道我应该研究什么会有帮助。我知道 pandas 合并功能,但它需要列的完全匹配,它是否可以帮助 pandassql,但我不确定如何将另一个数据库作为 Where postal code <= postal code low & postal code >= postal 的标准代码高?

有小费吗?

df的可视化:

在此处输入图像描述

标签: pythonpandasrangematchcriteria

解决方案


一种方法是进行嵌套列表理解:

df2["ID"] = [[idx for lo, hi, idx in zip(df["from postal code low"],
                                         df["from postal code high"],
                                         df["ID"]) if i in range(lo, hi+1)]
             for i in df2["from postal code"]]

print (df2)

  From country  from postal code to country  To postal code          ID
0           SE             21789         DE           91000       [ID2]
1           SE             41250         DE           91000  [ID4, ID5]

推荐阅读