【问题标题】:Remove paratheses with text inside from dataframe从数据框中删除带有文本的括号
【发布时间】:2021-12-14 00:29:46
【问题描述】:

如何从 df 列中删除括号中的文本(包括括号)? 例如:

index description
0 Beef (Cow))
1 Pork (Pig)
2 Hot Dog (Pig)
3 Chicken (Chicken)
4 Fish Sticks (Fish))

应该是:

index product
0 Beef
1 Pork
2 Hot Dog
3 Chicken
4 Fish Sticks

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    str.replace 与正则表达式一起使用,如下所示:

    df["description"] = df["description"].str.replace(r'\s+\([^()]*\)', '')
    
    • \s+ 匹配括号前的任何空格
    • \( 匹配 ( 字面意思
    • [^()]* 匹配任何不是() 的字符,* 使其重复
    • \) 匹配 ) 字面意思

    【讨论】:

    • 鉴于 OP 的示例,我认为您可以使用 df["description"].str.replace(r'\s+\(.*\)', ''),因为 .* 是贪婪的。但是,如果字符串可以包含多个“括号组”,即“...(x)...(y)”(OP的示例不包括),这将不起作用。所以我想你的解决方案更通用。
    【解决方案2】:

    一种使用pandas.Series.str.replace的方式:

    df["description"] = df["description"].str.replace("\(+.+?\)+", "", regex=True)
    print(df)
    

    输出:

       index   description
    0      0         Beef 
    1      1         Pork 
    2      2      Hot Dog 
    3      3      Chicken 
    4      4  Fish Sticks 
    

    【讨论】:

      猜你喜欢
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2022-11-16
      • 2022-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多