【问题标题】:How to extract string from Pandas Series using Regex that begins with any uppercase letter如何使用以任何大写字母开头的正则表达式从熊猫系列中提取字符串
【发布时间】:2019-10-10 15:30:47
【问题描述】:

我想将字符串系列提取到一个新系列中,该系列仅包含以原始系列数据的大写字母开头的字符串。

我之前在 pandas 系列中尝试过使用正则表达式,效果很好,所以我将其用作参考。下面的代码是我在当前问题中使用的代码。

harness['new'] = harness['Material'].str.extract('.*\-(.*)\-.*',expand=True)

下面的代码是我目前用来提取以大写字母开头的字符串

In [63]:
batch1['Wire Name'].head()

Out[63]:
0    2HC31A20
1    HC30A20
2    2HC42A20
3    2HC5H20
4    HC4M20

In [64]:
batch1['Grouping'] = batch1['Wire Name'].str.extract('^[A-Z].*',expand=True)
batch1['Grouping'].head()

Out [64]:
ValueError: pattern contains no capture groups

我希望结果是:

0    HC31A20
1    HC30A20
2    HC42A20
3     HC5H20
4     HC4M20

你觉得哪里不对?我已经检查了正则表达式页面和使用它的示例,但是当我使用上面的代码时它不起作用。

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    你可以使用:

    df = pd.DataFrame({'text': ['2HC31A20', 'HC30A20', '2HC42A20','2HC5H20', 'HC4M20']})
    df['text'].str.extract(r'(^[A-Z][\w]+)', expand=False)
    
    0        NaN
    1    HC30A20
    2        NaN
    3        NaN
    4     HC4M20
    

    说明:

    ^[A-Z] :这意味着仅以大写字母开头。
    [\w]+ : 这意味着取大写字母后的所有A-Z, a-z, 0-9, _

    【讨论】:

    • 正则表达式代码前的“r”是什么意思?就我而言,我想过滤 0,2,3 不要让它们为空
    • 谢谢 heena 我刚刚从您的回复中意识到我需要在主正则表达式代码之间添加括号,现在它可以工作了?
    【解决方案2】:

    您的正则表达式应该是“[A-Z].*”。 ^ 将尝试从字符串的开头匹配。

    【讨论】:

    • 这真的有效吗?我认为它仍然会抛出ValueError
    • 这个正则表达式通过在正则表达式之间添加括号来工作。谢谢拉卡
    【解决方案3】:

    在这里,我们可以简单地使用[A-Z] 作为左边界,然后向右滑动并收集其余字符串,可能类似于:

    (.+?)([A-Z].+)
    

    测试

    # coding=utf8
    # the above tag defines encoding for this document and is for Python 2.x compatibility
    
    import re
    
    regex = r"(.+?)([A-Z].+)"
    
    test_str = ("0    2HC31A20\n"
        "1    HC30A20\n"
        "2    2HC42A20\n"
        "3    2HC5H20\n"
        "4    HC4M20\n")
    
    subst = "\\2"
    
    # You can manually specify the number of replacements by changing the 4th argument
    result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
    
    if result:
        print (result)
    
    # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
    

    正则表达式

    如果不需要此表达式,可以在 regex101.com 中修改或更改。

    正则表达式电路

    jex.im 可视化正则表达式:

    演示

    const regex = /(.+?)([A-Z].+)/gm;
    const str = `0    2HC31A20
    1    HC30A20
    2    2HC42A20
    3    2HC5H20
    4    HC4M20
    `;
    const subst = `$2`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    【讨论】:

    • JavaScript 演示对于 Python 问题并不是特别有用。仅供参考。回答这么简单的问题时,有一种矫枉过正的感觉;-)
    • 我还应该提到这是一个熊猫问题,所以你的 python 代码也没有帮助。 :(
    【解决方案4】:

    感谢我的代码通过在主正则表达式之间添加括号来工作

    In[63]:
    batch1['Wire Name'].head()
    
    Out[63]:
    0    2HC31A20
    1    HC30A20
    2    2HC42A20
    3     2HC5H20
    4     HC4M20
    Name: Wire Name, dtype: object
    
    
    In [147]:
    batch1['Grouping'] = batch1['Wire Name'].str.extract('([A-Z].*)',expand=True)
    batch1['Grouping'].head()
    
    Out[147]:
    0    HC31A20
    1    HC30A20
    2    HC42A20
    3     HC5H20
    4     HC4M20
    Name: Grouping, dtype: object
    

    我不知道为什么虽然我认为括号是用来选择我们要提取的正则表达式的哪一部分?

    不带括号不是会产生同样的结果吗?

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 2018-08-28
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2015-05-14
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多