【发布时间】:2018-03-30 13:35:55
【问题描述】:
我有两个看起来有点像下面的数据框(df1 中的Content 列实际上是一篇文章的全部内容,而不是像我的示例中那样,只有一句话):
PDF Content
1 1234 This article is about bananas and pears and grapes, but also mentions apples and oranges, so much fun!
2 1111 Johannes writes about apples and oranges and that's great.
3 8000 Content that cannot be matched to the anything in df1.
4 3993 There is an interesting piece on bananas plus kiwis as well.
...
(总计:5709 个条目)
Author Title
1 Johannes Apples and oranges
2 Peter Bananas and pears and grapes
3 Hannah Bananas plus kiwis
4 Helena Mangos and peaches
...
(总计:10228 个条目)
我想通过在df1 的Content 中搜索df2 中的Title 来合并两个数据框。如果标题出现在内容的前 2500 个字符中的某处,则表示匹配。
注意:重要的是保留来自df1 的所有 条目。相反,我只想保留来自df2 的匹配项(即左连接)。
注意:所有Titles 都是唯一值。
所需的输出(列顺序无关紧要):
Author Title PDF Content
1 Peter Bananas and pears and grapes 1234 This article is about bananas and pears and grapes, but also mentions apples and oranges, so much fun!
2 Johannes Apples and oranges 1111 Johannes writes about apples and oranges and that's great.
3 NaN NaN 8000 Content that cannot be matched to the anything in df2.
4 Hannah Bananas plus kiwis 3993 There is an interesting piece on bananas plus kiwis as well.
...
我想我需要 pd.merge 和 str.contains 之间的组合,但我不知道怎么做!
【问题讨论】:
-
如果有多个匹配项,您希望/期望什么行为?
-
标题列中的所有条目都是唯一的。关于 Content 列,我希望 Title 条目与 Content 条目中找到的第一个匹配项匹配。
-
“第一个找到的匹配”如...?在数据集中排在第一位(逐行)还是在字符串中的位置排在第一位?
-
尝试一个完整的笛卡尔连接然后设计你自己的过滤器?
-
我已经编辑了我的问题,参见 PDF 1234,同时提到了“香蕉、梨和葡萄”以及“苹果和橙子”。所以,首先是在字符串中的位置。虽然我必须说两个标题不太可能同时出现在前 2500 个字符中。
标签: python regex pandas dataframe merge