【发布时间】:2020-08-25 23:49:04
【问题描述】:
我正在尝试根据列值对之间的匹配来合并两个数据框。但是,从一个数据帧到下一个数据帧的列值并不准确。这些对是使用瑞士坐标系的坐标,但从每个 df 中的稍微不同的参考点测量。
this stackoverflow thread How to find the distance between 2 points in 2 different dataframes in pandas? 似乎是一个相关的查询,但不幸的是我没有完全理解响应。
我的数据示例:
df1 = pd.DataFrame({'Ecode': [2669827.294, 2669634.483, 2669766.266, 2669960.683],
'Ncode': [1261034.528, 1262412.587, 1261209.646, 1262550.374],
'shape': ['square', 'square', 'triangle', 'circle']})
df1
Ecode Ncode shape
0 2669827.294 1261034.528 square
1 2669634.483 1262412.587 square
2 2669766.266 1261209.646 triangle
3 2669960.683 1262550.374 circle
df2 = pd.DataFrame({'CoorE': [2669636, 2669765, 2669827, 2669961],
'CoorN': [1262413, 1261211, 1261032, 1262550],
'color': ['purple', 'blue', 'blue', 'yellow']})
df2
CoorE CoorN color
0 2669636 1262413 purple
1 2669765 1261211 blue
2 2669827 1261032 blue
3 2669961 1262550 yellow
我想比较位于两组坐标(例如“形状”和“颜色”)的数据。我想要的结果与最接近匹配的列对匹配:
CoorE CoorN color shape
0 2669636 1262413 purple square
1 2669765 1261211 blue triangle
2 2669827 1261032 blue square
3 2669961 1262550 yellow circle
有没有办法做到这一点?我曾尝试使用 merge_asof 但意识到它不能键入两个变量。我还看到线程根据纬度和经度计算这个。我可以编写一个函数,将 CoorE/CoorN 和 Ecode/Ncode 视为 x/y 坐标,并计算一对坐标之间的距离(可能有更好的方法,但我是新手):
import math
def calculateDistance(x1,y1,x2,y2):
dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return dist
print calculateDistance(x1, y1, x2, y2)
或类似的东西,但不知道如何使用这种函数根据最小距离比较和匹配来自两个单独数据帧的坐标对。真实的数据集也有大约 300 万个条目,我想知道最不占用内存的方法是什么。
【问题讨论】:
-
你的坐标在这个系统中吗? epsg.io/21781。如果是这样,您的示例数据似乎在 CH 之外
-
坐标来自这个系统:swisstopo.admin.ch/en/knowledge-facts/surveying-geodesy/… - 但是我在我发布的示例中打乱了这对,因为数据有些敏感。
-
我相信我实际上找到了使用复数的解决方案 - 我为坐标创建了一个列作为复数:2669636+1262413j,然后取所有可能对之间的最小距离以获得匹配。对于似乎有效的小例子,我还没有对完整的数据集进行测试。
-
有趣 - 我以为您在寻找最近的对,而不是可以在
merge_asof()中使用的值。已更新的答案可以满足您与几何距离的要求
标签: python pandas merge coordinates