【问题标题】:Use Regex to populate new column with substring from another column in Python [duplicate]使用正则表达式用 Python 中另一列的子字符串填充新列 [重复]
【发布时间】:2021-07-27 22:45:20
【问题描述】:

我有一个 df,我想在其中添加一列,从另一列中提取我需要的数据。我从中提取的列包含字符串,所以我猜我需要为此使用正则表达式或 Re。

我的 df 的简化示例:

Column A    Column B                                
1           I want (this text) only                    
2           I only want (this) text          
3           that appears (in) the parentheses
4           but not every line has
5           (parentheses) in it

所以我希望我的 df 看起来像这样:

Column A    Column B                            Column C                           
1           I want (this text) only              this
2           I only want (this) text              this
3           that appears (in) the parentheses    in
4           but not every line has
5           (parentheses) in it                  parentheses

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    如果您只想要括号内的 first 单词,则使用str.extract,如下所示:

    df["C"] = df["B"].str.extract(r'\((\S+)')
    

    如果您想要括号的全部内容,请使用:

    df["C"] = df["B"].str.extract(r'\((.*?)\)')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 2015-01-08
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多