【问题标题】:How can I put multiple conditions for detecting a pattern in pandas using regex如何使用正则表达式设置多个条件来检测熊猫中的模式
【发布时间】:2021-09-27 15:53:30
【问题描述】:

我有一个这样的数据框:

text

Is it possible to apply [NUM] times
Is it possible to apply [NUM] time
Called [NUM] hour ago
waited [NUM] hours
waiting [NUM] minute
waiting [NUM] minutes???
Are you kidding me !
Waiting?

我希望能够检测到具有"[NUM] time" or "[NUM] times" or "[NUM] minute" or "[NUM] minutes" or "[NUM] hour" or "[NUM] hours" 的模式。另外,如果它有"!" (or more than one !)"??" (at least two ?)

所以结果应该是这样的:

text.                                  available

Is it possible to apply [NUM] times.   True
Is it possible to apply [NUM] time.    True
Called [NUM] hour ago                  True
waited [NUM] hours                     True
waiting [NUM] minute                   True
waiting [NUM] minutes???               True
Are you kidding me !                   True
Waiting?                               False
I didn't like it                       False

所以我想要这样的东西,但不知道如何将所有这些条件放在一起:

df["available"] = df['text'].apply(lambda x: re.match(r'[\!* | \?+ | [NUM] time | [NUM] hour | [NUM] minute]')

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    您可以将Series.str.contains 与正则表达式一起使用:

    import pandas as pd
    df = pd.DataFrame({'text':["Is it possible to apply [NUM] times","Is it possible to apply [NUM] time","Called [NUM] hour ago","waited [NUM] hours","waiting [NUM] minute","waiting [NUM] minutes???","Are you kidding me !","Waiting?", "I didn't like it"]})
    df['available'] = df['text'].str.contains(r'\[NUM]\s*(?:hour|minute|time)s?\b|!|\?{2}', regex=True)
    ## => df['available']
    #     0     True
    #     1     True
    #     2     True
    #     3     True
    #     4     True
    #     5     True
    #     6     True
    #     7    False
    #     8    False
    

    请参阅regex demo详情

    • \[NUM] - [NUM] 字符串
    • \s* - 零个或多个空格
    • (?:hour|minute|time) - 匹配 hourminutetime 的非捕获组
    • s? - 一个可选的s
    • \b - 单词边界
    • | - 或
    • ! - 一个 ! 字符
    • | - 或
    • \?{2} - 两个问号。

    【讨论】:

    • 非常感谢!!!
    • 您是否知道为什么当我使用文本而不是数据框中的文本时相同的代码不起作用? text="Been on hold for [NUM] minutes at that number, AFTER it wouldn't let me cancel the reservation." 然后 available = re.match('r\[NUM]\s*(?:hour|minute|time|number|hr|Hr)s?\b|!{2}|\?{2}', text) available 是 NONE。抱歉,如果我没有在regex 中打开一个新问题,因为我是新的,我认为这可能是一个简单的问题,并且我收到了很多负面评价 :((((
    • @sariii 正确,你会在这样的问题上得到很多反对意见。答案是“使用re.search”。见What is the difference between re.search and re.match?
    • 是的,我想如果我发布这个问题,我的分数会降到 -1000 :)))。感谢分享链接。但是,searchmatch 都不会返回任何合理的输出。两者都返回None。我理解它们之间区别的方式仅适用于句子中存在new line^ 的情况。但是,我的情况只是一行,所以我认为matchsearch 都应该能够完成这项工作。我在这里错过了什么吗?
    • @sariii 您的 regex 有效,您只是通过将原始字符串文字 r 前缀移动到字符串文字本身来打错字。见this Python demo
    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2015-11-18
    • 2023-01-31
    • 2019-10-19
    相关资源
    最近更新 更多