python - 根据同一行中是否存在单词查找两列是否匹配

标签 python pandas dataframe

我有一个包含两列感兴趣的数据框。我想尝试按单词比较两列并找出是否有单词重叠。如果是这样,我想附加一列来指示在该行中找到了匹配的单词。

这是我的数据框的示例:

df
    name1      name2
0   cat nip    giant cat
1   bad dog    blue sky
2   slow snail slimy snail
3   tall tree  big boy

这就是我想要的:

df
    name1      name2       found
0   cat nip    giant cat   True
1   bad dog    blue sky    False
2   slow snail slimy snail True
3   tall tree  big boy     False

我尝试过很多方法。一种方法是使用此代码:

df['found'] = df['name1'].apply(lambda x: any(i in df['name2'] for i in x))

这不起作用。第二种方法是使用此代码:

glossary = list(set(df['name1']))
pattern = '|'.join(glossary)
check = df[(df.name1.str.contains(pattern))& 
        (df.name2.str.contains(pattern))]

这段代码也不起作用,它正在创建一个新的数据帧(我不想要)。而且这两种方法都非常慢。有什么想法可以正确地做到这一点吗?

此外,我已经尝试过 isin 方法:

df['found'] = df['name1'].isin(df['name2'])

这也不起作用。它给了我很多错误的True标签。

最佳答案

您可以在系列之间使用 & 来使用简单的解决方案。

第一transform您要设置的列表

transf_1 = df.name1.str.split(" ").transform(set)
transf_2 = df.name2.str.split(" ").transform(set)

然后就

>>> transf_1 & transf_2.values

0     True
1    False
2     True
3    False

关于python - 根据同一行中是否存在单词查找两列是否匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51052867/

相关文章:

python - Pandas 适用,但仅适用于满足条件的行

dataframe - 在 DataFrame 链中分配中间结果

python - Selenium : WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

python - 将函数应用于 groupby 函数

Python:无法导入名称/IndexError:列表索引超出范围

javascript - Tensorflow 和 Tensorflow.js 的区别?

python - 使用来自同一数据帧的 x 和 y 绘制直方图

python - 使用掩码估算混合类型 DataFrame 子集中的缺失值

python - 使用 python 将数据文件从源工作表转换为目标工作表格式。

Python Pandas : How to groupby aggregate using a function that returns pd. 系列