【问题标题】:Pandas - Get values within parentheses of a panda dataframe columnPandas - 获取熊猫数据框列括号内的值
【发布时间】:2016-10-21 14:04:27
【问题描述】:

我的df 有 2 列:

Name    Attr
a(bc)
b(aca)
(cba)

我希望列 Attr 的值包含在列 Name 的括号内

Name    Attr
a(bc)   bc
b(aca)  aca
(cba)   cba

我试过了:

df['Attr'] = re.findall('\(.*?\)',df['Name'].astype('str'))

TypeError: expected string or buffer

非常感谢任何帮助

【问题讨论】:

    标签: python regex pandas dataframe parentheses


    【解决方案1】:

    使用str.extract:

    df['Attr'] = df['Name'].str.extract(r"\(([A-Za-z]+)\)", expand=False)
    print (df)
         Name Attr
    0   a(bc)   bc
    1  b(aca)  aca
    2   (cba)  cba
    

    或将() 添加到您的regex

    df['Attr'] = df['Name'].str.extract(r"\((.*?)\)", expand=False)
    print (df)
         Name Attr
    0   a(bc)   bc
    1  b(aca)  aca
    2   (cba)  cba
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2022-01-11
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多