python - 在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的可视化:
解决方案
一种方法是进行嵌套列表理解:
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]
推荐阅读
- c++ - 通过套接字发送的自定义数据包
- javascript - Bot 框架 (v4) - 如何从自定义提示验证中获取状态
- javascript - 如何从脚本效果后渲染 adobe?
- flutter - Flutter in_app_purchase queryPastPurchase 在 iOS 上返回 null
- javascript - 递归拆分包含 html 元素的字符串并在 javascript 中获取特定值
- c# - 如何在 ListView C# XAML XAMARIN 中反序列化 JSON
- apktool - 如何修复 brut.androlib.AndrolibException: brut.common.BrutException: could not exec (exit code = -1073741515)
- leaflet - 如何在图层组中添加 wms tilelayers
- regex - 在awk中捕获双引号之间的单词
- bash - 如何使用bash合并多个文本文件并保留列顺序