在数据帧的每一行中搜索时,如何从关键字列表中获得匹配的关键字?

2024-09-30 20:34:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框中有一列“Description”,我正在这个列中搜索关键字列表。如果关键字出现在特定行中,我可以返回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

Tags: 数据falsetruedf列表new关键字description
2条回答

如果description中的值总是用空格隔开,那么可以使用

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

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

它将返回一个set对象,您可以随意修改它

这种方法的一个优点是它可以提供多个匹配字符串

使用contains而不是extract的模式有些不同:

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

相关问题 更多 >