包含敬语的名字如-
我想从名称中删除所有前缀和后缀,特别是熊猫名称中使用的所有不同类型的敬语。
作为输出,我想要-
我使用了一些代码,但在某些情况下不起作用,我想要一个非常健壮的代码。有没有办法做到这一点?
答案 0 :(得分:2)
您可以替换与所有前缀匹配的正则表达式。例如:
>>> 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)
如果您想包含其他标题,只需更新正则表达式
>>> 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