【问题标题】:Remove numbers inside parenthesis in pandas dataframe删除熊猫数据框中括号内的数字
【发布时间】:2021-11-01 12:42:04
【问题描述】:

我有一个包含类似数据的数据框

column1
-----------
Hello (120)
234
World (22

我正在尝试删除所有部分,例如 (120)(22。我写的代码是:

df['column1'] = df['column1'].str.replace(r"\((\d+)\)", "", regex = True)
df['column1'] = df['column1'].str.replace(r"\((\d+)", "", regex = True)

我的预期输出是:

column1
--------
Hello 
234
World 

但我得到的是:

column1
--------
Hello 

World 

谁能向我解释为什么 234 被删除?

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    你可以使用:

    >>> df['column1'].str.replace(r"\s*\(\d+\)?", "", regex=True)
    0    Hello
    1      234
    2    World
    Name: column1, dtype: object
    

    你的代码对我来说很好用,除了 '(' 之前的空格

    【讨论】:

    • @KaziSohan。你有时间检查答案吗?
    【解决方案2】:

    尝试模式\s*\(\d+(?:\))?。它将替换以一个或多个空格和一个包含数字的左括号开头的任何内容,以/不以右括号结尾

    >>> df['column1'].str.replace('\s*\(\d+(?:\))?', '', regex=True)
    
    0    Hello
    1      234
    2    World
    Name: column1, dtype: object
    

    【讨论】:

    • @Corralien,正则表达式中没有捕获组,如果您试图指向 (?:\))? 部分,那也不是捕获组
    • 抱歉,我想我需要新眼镜 :-)
    • 正则括号的非捕获版本。匹配括号内的任何正则表达式,但组匹配的子字符串在执行匹配后无法检索或稍后在模式中引用。来自(?:...)的文档
    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2020-08-23
    • 2021-12-17
    • 2016-10-21
    相关资源
    最近更新 更多