【问题标题】:See if a list of strings in df1[Keyword'] is found anywhere in a df2['Description'] and drop rows if df2 if no matches查看是否在 df2['Description'] 的任何位置找到 df1[Keyword'] 中的字符串列表,如果 df2 没有匹配则删除行
【发布时间】:2020-12-18 23:42:56
【问题描述】:

我有两个数据框,df1df2

df1 在名为“Keyword”的列中包含一个字符串列表。我正在尝试查看是否在第二个数据帧 df2['Description'] 中找到这些字符串,如果它们不包含 df1['Keyword'] 中的至少一个字符串,则删除 df2 中的行

df1                 df2
Keyword             Description   
Car                 I like driving my **car**      <- Keep
Dog                 No keywords here!              <- Drop Row
Elephant            Bart gets an **Elephant**      <- Keep
Bat                 No keywords in this sentence   <- Drop Row

我的尝试:

df2['Check'] = df1["Keyword"].isin(df2[Description"])

即使有匹配项,所有内容都会提升为 FALSE。这个想法是在代码运行后删除所有包含 FALSE 的行。

【问题讨论】:

  • 它们是否必须在两个数据框中位于同一行中?或者,关键字可以在一个数据框中的一行中,在另一个数据框中的另一行中

标签: python python-3.x pandas dataframe


【解决方案1】:

您可以使用 lookup() 函数,它为 DataFrame 返回基于标签的索引函数

def lookup(x, values):
    for value in values:
        if value.lower() in x.lower():
            return value

然后你可以将函数应用到 df2 df2['df2'] = df2['B'].apply(lambda x: lookup(x, df1['df2']))

【讨论】:

  • 非常感谢!有没有办法使用这种方法将所有关键字匹配项提取到新列中? ['Check 2'] 和 ['Check 3'] 列以及其他匹配项。谢谢!
【解决方案2】:

解决方案 1: 您可以创建由| 连接的一长串唯一值,并使用str.contains 搜索这些值并传递case=False

df1['Check'] = df2['Description'].str.contains('|'.join(df1['Keyword'].unique()), case=False)
Out[1]: 
    Keyword  Check
0       Car   True
1       Dog  False
2  Elephant   True
3       Bat  False

解决方案 2: 您可以使用列表推导来检查 any 值是否在列中。确保使用lower 规范化大小写,以便您得到匹配,因为python 区分大小写::

df1['Check'] = (df1["Keyword"].apply(
                                     lambda x: any([True 
                                     for y in df2['Description'].str.casefold()
                                     if x.lower() in y])))
#str.casefold() is potentially more robust than str.lower() if text is not in English
df1
Out[2]: 
    Keyword  Check
0       Car   True
1       Dog  False
2  Elephant   True
3       Bat  False

从那里,只需 df1[df1['Check']]:

    Keyword    Check
0   Car         True
2   Elephant    True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 2020-09-26
    相关资源
    最近更新 更多