包含敬语的名称,如-
- 先生埃文斯
- 小Aley Fred
我想删除名字的所有前缀和后缀,特别是熊猫名字中使用的所有不同种类的敬语。
作为输出,我想要-
- Evans
- Aley Fred
我使用了一些代码,但在某些情况下它不起作用,我想要一个非常健壮的代码。有办法做到这一点吗?
您可以有一个匹配所有前缀的regex替换。例如:
>>> pat = r'(Mr|Jr).?'
# 'col_name' is the name of the column where your names are.
>>> df['col_name'].replace(pat,'',regex=True)
#If you want your change to be applied inplace just add `inplace`:
>>> df['col_name'].replace(pat,'',regex=True, inplace=True)
编辑
如果你想包括其他标题,你只需更新regex
>>> pat=r'(,|.|Mrs|Jr|Dr|Mr)'
>>> df
ID Name
0 1 Mr. Evans
1 2 Aley Fred,Jr.
2 3 Mrs. Sheen,Jr.
>>> df['Name'].replace(pat,'',regex=True)
0 Evans
1 Aley Fred
2 Sheen