【问题标题】:Merge Dataframes on basis of coordinates having no common columns根据没有公共列的坐标合并数据框
【发布时间】:2019-04-15 01:43:51
【问题描述】:

输入:

df1

Pg  x0      y0      x1      y1      Text
1   521.3   745.92  537.348 754.097 word1
1   538.982 745.92  580.247 754.097 word2
1   527.978 735.253 572.996 747.727 word3
2   268.985 732.36  341.59  746.636 word4
2   344.443 732.36  390.175 746.636 word5

df2

Pg  x0      y0      x1      y1      Text                T   R   C
1   507.6   730.8   593.76  754.8   word1 word2 word3   1   1   2
2   334.56  732.36  401.34  746.636 word5               2   3   1

预期输出:

Pg  x0      y0      x1      y1      Text    T   R   C
1   521.3   745.92  537.348 754.097 word1   1   1   2
1   538.982 745.92  580.247 754.097 word2   1   1   2
1   527.978 735.253 572.996 747.727 word3   1   1   2
2   268.985 732.36  341.59  746.636 word4           
2   344.443 732.36  390.175 746.636 word5   2   3   1

我需要根据坐标(重叠)和基于非文本的方法来查找 df1 中的所有单词都存在于 df2 中。在此之后,我需要将列 [T, R, C] 的值从 df2 复制到 df1。

例如:df2 的第一行的坐标与 df1 的 word1、word2、word3 的坐标重叠。此处的重叠意味着 df1 中一行的 bbox(x0, y0, x1, y1) 应位于 df2 特定行的 bbox(x0, y0, x1, y1) 内。

我的方法:

我正在迭代 df2 中的每一行,然后比较 df1 中的每一行坐标以找到任何重叠,然后合并数据帧。

for i, r in df2.iterrows():
    df1.loc[
                (df1.x0 >= r.x0) &
                (df1.y0 >= r.y0) &
                (df1.x1 <= r.x1) &
                (df1.y1 <= r.y1) , 'flag'] = 1

    df1.loc[df.flag == 1, ['T', 'R', 'C']] = r.T, r.R, r.C

问题是整个过程按预期正常工作,但需要大量时间才能运行。运行 df1 = 20,000 行和 df2 = 3500 行大约需要 90 seconds

【问题讨论】:

  • 您能否发布合并数据框的工作代码,以便我们就如何改进它提出具体建议?

标签: python pandas dataframe geometry


【解决方案1】:

您可以使用apply 和屏蔽。示例:

def compare(row):
    mask = df2[
        (df2['x0'] <= row['x0']) &
        (df2['x1'] >= row['x1']) &
        (df2['y0'] <= row['y0']) &
        (df2['y1'] >= row['y1'])
    ]
    if mask.empty:
        return row
    row['T'] = mask['T'].tolist()[0]
    row['R'] = mask['R'].tolist()[0]
    row['C'] = mask['C'].tolist()[0]

return row

result = df1.apply(compare, axis=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2023-01-12
    相关资源
    最近更新 更多