【问题标题】:pandas extractall matching熊猫提取所有匹配
【发布时间】:2017-05-15 20:51:54
【问题描述】:

如何将以下内容与 pandas extractall 正则表达式匹配:

stringwithinmycolumn
stuff, Duration: 15h:22m:33s, notstuff,
stuff, Duration: 18h:22m:33s, notstuff,

目前,我正在使用以下内容:

df.message.str.extractall(r',([^,]*?): ([^,:]*?,').reset_index()

预期输出:

              0              1
match    
    0  Duration    15h:22m:33s
    1  Duration    18h:22m:33s

到目前为止,我无法匹配。

【问题讨论】:

    标签: python regex python-3.x pandas


    【解决方案1】:

    你可以使用

    ,\s*([^,:]+):\s*([^,]+),
    

    regex demo

    匹配:

    • , - 逗号
    • \s* - 0+ 个空格
    • ([^,:]+) - 第 1 组: - 除 ,: 之外的 0+ 个字符
    • : - 冒号
    • \s* - 0+ 个空格
    • ([^,]+) - 第 2 组:, 以外的一个或多个字符
    • , - 逗号(实际上可以删除,但可能会保留以确保更安全的匹配。)

    请注意,当您需要从长字符串中提取结构化信息时,您可以考虑使您的正则表达式更加精确。因此,您可能希望使用字母匹配模式来匹配Duration,并且仅使用数字、冒号、hms 来提取时间值。所以,模式会变得更加冗长:

    ,\s*([A-Za-z]+):\s*([\d:hms]+)
    

    但更安全。见another regex demo

    【讨论】:

      【解决方案2】:
      In [246]: x.message.str.extractall(r',\s*(\w+):\s*([^,]*)').reset_index(level=0, drop=True)
      Out[246]:
                    0            1
      match
      0      Duration  15h:22m:33s
      0      Duration  18h:22m:33s
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-15
        • 1970-01-01
        • 2018-04-28
        • 2017-06-03
        • 1970-01-01
        • 1970-01-01
        • 2019-10-09
        • 2021-12-21
        相关资源
        最近更新 更多