Pandas - Get values within parentheses of a panda dataframe column [duplicate]

给你一囗甜甜゛ 提交于 2020-06-08 20:03:36

问题


My df has 2 columns:

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

I would like the column Attr to have the values within parentheses of column Name

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

I tried:

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

TypeError: expected string or buffer

Really appreciate any help


回答1:


Use 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

Or add () to your 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


来源:https://stackoverflow.com/questions/37920443/pandas-get-values-within-parentheses-of-a-panda-dataframe-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!