【问题标题】:How to get the keyword that was matched from a list of keywords while searching in every row of a dataframe?如何在数据框的每一行中搜索时从关键字列表中获取匹配的关键字?
【发布时间】:2020-02-05 03:36:38
【问题描述】:

我的数据框中有一列“描述”,我正在此列中搜索关键字列表。如果关键字出现在特定行中,我能够返回 True 或 False 值。我想再添加一列,显示列表中的哪个关键字与该行中的数据匹配。

例如:

content = ['paypal', 'silverline', 'bcg', 'onecap']

#dataframe df

Description        Debit  Keyword_present 

onech xmx paypal    555     True
xxl 1ef yyy         141     False
bcg tte exact       411     True

新列应如下所示:

 Keyword
 paypal
 NA
 bcg

到目前为止,如果存在关键字,我已经尝试获取 T/F 值。

#content is my list of keywords

present = new_df['Description'].str.contains('|'.join(content)) 

new_df['Keyword Present'] = present

【问题讨论】:

  • 发布你写到这里的代码

标签: python regex pandas dataframe


【解决方案1】:

如果您在 description 中的值始终用空格分隔,您可以使用类似

content = ['paypal', 'silverline', 'bcg', 'onecap']
content = set(content)

df['keyword_matched'] = df['Description'].apply(lambda x: set(x:x.split(' ')).intersection(content)

它会返回一个集合对象,你可以随意修改它。

这种方法的一个优点可能是它可以给出多个匹配的字符串,

【讨论】:

    【解决方案2】:

    使用 extract 代替 contains,但模式略有不同:

    pattern = '(' + '|'.join(content) + ')'
    df['Keyword Present'] = df.Description.str.extract(pattern)
    

    输出:

            Description  Debit  Keyword_present Keyword Present
    0  onech xmx paypal    555             True          paypal
    1       xxl 1ef yyy    141            False             NaN
    2     bcg tte exact    411             True             bcg
    

    【讨论】:

    • 所以基本上你将列表作为单个字符串并返回在特定行中完全匹配的单词。
    猜你喜欢
    • 2016-03-25
    • 2011-11-22
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多