从熊猫的名称(前缀和后缀)中删除敬语

时间:2021-01-03 18:35:18

标签: python-3.x pandas

包含敬语的名字如-

  1. 先生埃文斯
  2. Aley Fred,

我想从名称中删除所有前缀和后缀,特别是熊猫名称中使用的所有不同类型的敬语。

作为输出,我想要-

  1. 埃文斯
  2. 艾利·弗雷德

我使用了一些代码,但在某些情况下不起作用,我想要一个非常健壮的代码。有没有办法做到这一点?

1 个答案:

答案 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