python - Pandas 按坐标合并

标签 python pandas merge

我正在尝试合并两个 pandas 表,我在其中找到 df2 中的所有行,这些行的坐标接近 df1 中的每一行。示例如下。

df1: 
   x  y val
0  0  1   A
1  1  3   B
2  2  9   C

df2:
    x    y  val
0  1.2  2.8   a
1  0.9  3.1   b
2  2.0  9.5   c

desired result:
   x  y val_x val_y
0  0  1     A   NaN
1  1  3     B     a
2  1  3     B     b
3  2  0     C     c

df1 中的每一行在 df2 中可以有 0 个、1 个或多个对应条目,找到匹配应该用笛卡尔距离来完成:

(x1 - x2)^2 + (y1 - y2)^2 < 1

输入数据帧具有不同的大小,即使在本例中它们没有。我可以通过迭代 df1 中的行并在 df2 中找到接近值来接近,但我不确定从那里该做什么:

for i, row in df1.iterrows():
    df2_subset = df2.loc[(df2.x - row.x)**2 + (df2.y - row.y)**2 < 1.0]
    # ?? What now?

如有任何帮助,我们将不胜感激。我用 ipython 笔记本做了这个例子,所以你可以在这里查看/访问:http://nbviewer.ipython.org/gist/anonymous/49a3d821420c04169f02

最佳答案

我找到了答案,尽管我对必须遍历 df1 中的行并不是很满意。在这种情况下,只有几百个,所以我可以处理它,但它不会像其他东西那样扩展。解决方案:

df2_list = []
df1['merge_row'] = df1.index.values  # Make a row to merge on with the index values
for i, row in df1.iterrows():
    df2_subset = df2.loc[(df2.x - row.x)**2 + (df2.y - row.y)**2 < 1.0]
    df2_subset['merge_row'] = i # Add a merge row
    df2_list.append(df2_subset)
df2_found = pd.concat(df2_list)

result = pd.merge(df1, df2_found, on='merge_row', how='left')

关于python - Pandas 按坐标合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28969957/

相关文章:

git - Intellij 作为 merge 工具无法正确检测编码

python - Pandas 数据框合并

r - 在替换 NA 时合并组中的行

python - 具有两个 row_colors 的 Seaborn clustermap

python - 从 matplotlib.pyplot 导入 plt ImportError : No module named 'matplotlib'

python - 如何根据另一个数据框中的列填充数据框中的空值?

如果缺少,Python 将元素添加到列表中的列表

python - 使用 pygame 创建 slider

Python Tkinter 应用程序未正确退出

python - 如何选择 Pandas 中的行范围?