从另一个数据帧的列表中查找数据帧中的字符串



我在python中有两个panda数据帧,设置如下:

Dataframe 1:
ID      Paragraph
1      'A B C D E'
2      'A F G H L'
3      'B J P Q W'
4      'G F D S A'

其中段落是由多个单词组成的字符串。

Dataframe 2: 
ID      Name        Words
1      First      ['A', 'F']
2      Second     ['B', 'Z']
3      Thrird     ['P', 'Q']
4      Fourth     ['H', 'J']

名称只是识别单词的字符串。Words是一个字符串列表。

所以我想做的是有一个表达式,它将识别数据帧1中的哪些段落包含数据帧2中的单词。我想把单词的名称存储在数据帧1的一个新列中。新列将包含段落中出现单词中的单词的所有名称的列表。顺序无关紧要,列表中不得有重复项。

例如:

New Dataframe 1:
ID      Paragraph             Names
1      'A B C D E'       [First, Second]
2      'A F G H L'       [First, Fourth]
3      'B J P Q W'   [Second, Third, Fourth]
4      'G F D S A'           [First]

我只能制作一个深度嵌套循环并需要很长时间才能执行的解决方案。有没有一个计算时间更短的解决方案?我的想法可能是使用loc和/或lambda函数。

如有任何帮助,我们将不胜感激!

如果有什么我需要澄清的,请告诉我。

英语不是我的第一语言,所以如果需要的话,我可以尝试解释更多。

谢谢

以下是伪数据帧的代码:

data_1 = {'Paragraph': ['A B C D E', 'A F G H L', 'B J P Q W', 'G F D S A']}
df_1 = pd.DataFrame(data_1)
data_2 = {'Name': ['First', 'Second', 'Third', 'Fourth'],
'Words': [['A', 'F'], ['B', 'Z'], ['P', 'Q'], ['H', 'J']]}
df_2 = pd.DataFrame(data_2)

您可以splitexplode段落。然后CCD_ 3分解的df_2的每个单词的名称。最后,聚合为set以具有唯一值:

s = df_2.explode('Words').set_index('Words')['Name']
df_1['Names'] = (df_1['Paragraph'].str.split()
.explode().map(s).dropna()
.groupby(level=0).agg(set)
)

输出:

Paragraph                    Names
0  A B C D E          {Second, First}
1  A F G H L          {Fourth, First}
2  B J P Q W  {Third, Second, Fourth}
3  G F D S A                  {First}

最新更新