【问题标题】:include one word and exclude another python包含一个单词并排除另一个 python
【发布时间】:2018-03-14 12:14:55
【问题描述】:

背景:我有以下数据框

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 是否存在并返回一个布尔值(如果paid 在文本列中的任何位置返回True,如果paid 不存在则返回False。但我会喜欢排除单词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) 我的目标

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    使用lambda:

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

    【讨论】:

      【解决方案2】:

      您可以使用逻辑和来检查这两个条件。

      (df.text.str.contains('paid')) & (~df.text.str.contains('volunteer'))
      Out[14]: 
      0     True
      1    False
      2    False
      Name: text, dtype: bool
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-22
        • 2011-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多