答案 0 :(得分:4)
如果你想要摆脱连续的重复 ,这应该足够了:
df['Desired'] = df['Current'].str.replace(r'\b(\w+)(\s+\1)+\b', r'\1')
df
Current Desired
0 Racoon Dog Racoon Dog
1 Cat Cat Cat
2 Dog Dog Dog Dog Dog
3 Rat Fox Chicken Rat Fox Chicken
<强>详情
\b # word boundary
(\w+) # 1st capture group of a single word
(
\s+ # 1 or more spaces
\1 # reference to first group
)+ # one or more repeats
\b
来自here的正则表达式。
要删除非连续重复项,我建议一个涉及OrderedDict
数据结构的解决方案:
from collections import OrderedDict
df['Desired'] = (df['Current'].str.split()
.apply(lambda x: OrderedDict.fromkeys(x).keys())
.str.join(' '))
df
Current Desired
0 Racoon Dog Racoon Dog
1 Cat Cat Cat
2 Dog Dog Dog Dog Dog
3 Rat Fox Chicken Rat Fox Chicken