gpt4 book ai didi

python - 包含一个词并排除另一个 python

转载 作者:行者123 更新时间:2023-11-28 19:03:53 25 4
gpt4 key购买 nike

背景:我有以下数据框

import pandas as pd
d = {'text': ["paid", "paid and volunteer", "other phrase"]}
df = pd.DataFrame(data=d)
df['text'].apply(str)

输出:

                   text
0 paid
1 paid and volunteer
2 other phrase

目标:

1) 检查每一行以确定 paid 是否存在并返回一个 bool 值(如果 paid 位于文本列中的任何位置,则返回 TrueFalse 如果 paid 不存在。但我想排除 volunteer 这个词。如果 volunteer 存在,结果应该是 false

2) 用结果创建一个新列

期望的输出:

                   text     result
0 paid true
1 paid and volunteer false
2 other phrase false

问题:我正在使用以下代码

df['result'] = df['text'].astype(str).str.contains('paid') #but not volunteer

我检查了How to negate specific word in regex?它显示了如何排除一个词,但我不确定如何在我的代码中包含

问题:我如何更改我的代码以实现我的目标 1) 和 2)

最佳答案

使用lambda:

df['result'] = df['text'].apply(lambda row: True if ('paid' in row) and ('volunteer' not in row) else False)

关于python - 包含一个词并排除另一个 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269593/

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