我的dataframe是:
NameID 0 Mandalapu Harish (MH) (34567) 1 Roopa S (RS) (7861) 2 Geetha Harish (GH A) (9234178)
我如何使用pandas删除最后一组括号?
Name 0 Mandalapu Harish (MH) 1 Roopa S (RS) 2 Geetha Harish (GH A)
6tdlim6h1#
使用str.replace:
str.replace
df['Name'] = df['NameID'].str.replace(r'\s*\([^)]+\)$', '', regex=True)
df['Name'] = df.pop('NameID').str.replace(r'\s*\([^)]+\)$', '', regex=True)
输出:
NameID Name 0 Mandalapu Harish (MH) (34567) Mandalapu Harish (MH) 1 Roopa S (RS) (7861) Roopa S (RS) 2 Geetha Harish (GH A) (9234178) Geetha Harish (GH A)
6kkfgxo02#
另一种可能的解决方案基于pandas.Series.str.rsplit:
pandas.Series.str.rsplit
df['NameID'].str.rsplit(n=1).str[0]
0 Mandalapu Harish (MH) 1 Roopa S (RS) 2 Geetha Harish (GH A) Name: NameID, dtype: object
2条答案
按热度按时间6tdlim6h1#
使用
str.replace
:df['Name'] = df.pop('NameID').str.replace(r'\s*\([^)]+\)$', '', regex=True)
。*输出:
6kkfgxo02#
另一种可能的解决方案基于
pandas.Series.str.rsplit
:输出: