【问题标题】:Select and concatenate DataFrame rows based on list of tuples根据元组列表选择并连接 DataFrame 行
【发布时间】:2021-01-28 13:31:12
【问题描述】:

我有两个这样的 DataFrame:

df_cells = pd.DataFrame({
    'left': [1095, 257],
    'top': [1247, 1148],
    'right': [1158, 616],
    'bottom': [1273, 1176] 
})

df_text = pd.DataFrame({
    'words': ['Hello', 'world', 'nice day', 'have a'],
    'left': [1097, 1099, 258, 259],
    'top': [1248, 1249, 1156, 1153],
    'right': [1154, 1156, 615, 614],
    'bottom': [1269, 1271, 1175, 1172] 
})

df_cells 包含图像上短语的边界框坐标,df_text 包含图像上的单词及其边界框坐标。

我创建了一个元组列表,其中短语和单词的边界框根据 lefttoprightbottom 值匹配,如下所示:

overlap = [(0,0), (1,0), (2, 1), (3, 1)]

其中元组的第一个元素是df_text 的索引值,第二个元素是df_cells 的匹配索引值。

我想选择,将基于重叠的行组合成一个新的数据框,如下所示:

Words                df_cells.left    df_cells.top    df_cells.right   df_cells.bottom
Hello                1095             1247            1158             1273
world                1095             1247            1158             1273
Have a               257              1148            616              1176
nice day             257              1148            616              1176

然后将具有相同lefttoprightbottom 的单词连接起来,如下所示:

Words                df_cells.left    df_cells.top    df_cells.right   df_cells.bottom
Hello world          1095             1247            1158             1273
Have a nice day      257              1148            616              1176

不胜感激。

【问题讨论】:

  • 我不明白“匹配”的定义。你能用数学方法说明匹配条件吗?

标签: python python-3.x pandas dataframe


【解决方案1】:

我认为您可以使用列表理解创建的索引将值直接分配给df_text

df_text.iloc[[i[0] for i in overlap], 1:] = df_cells.iloc[[i[1] for i in overlap]].to_numpy()

print (df_text)

      words  left   top  right  bottom
0     Hello  1095  1247   1158    1273
1     world  1095  1247   1158    1273
2  nice day   257  1148    616    1176
3    have a   257  1148    616    1176

print (df_text.groupby(["left", "top", "right", "bottom"], as_index=False).agg({"words":" ".join}))

   left   top  right  bottom            words
0   257  1148    616    1176  nice day have a
1  1095  1247   1158    1273      Hello world

【讨论】:

  • 运行代码时出现以下错误(适用于我的实际 dfs 和列表) ValueError: Must have equal len keys and value when setting with an ndarray
  • 意味着您的任一 df 中都有更多列。请始终提供与您的实际数据相似的示例数据。
  • 对不起,那是我的错误。重启后我忘记在笔记本中重新运行一个单元格,该单元格删除了一列以使列数相等。
猜你喜欢
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
相关资源
最近更新 更多