gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:46 25 4
gpt4 key购买 nike

我的数据框中有一列“描述”,我正在该列中搜索关键字列表。如果特定行中存在关键字,我能够返回 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

最佳答案

代替 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

关于python - 在数据框的每一行中搜索时,如何从关键字列表中获取匹配的关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58276351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com