python删除重复单词,Python数据框:删除Python列中同一单元格中的重复单词

Below shows a column with data I have and another column with the de-duplicated data I want.

bHyD1.png

I honestly don't even know how to start doing this in Python code. I've read a couple of posts on this in R, but not in Python.

解决方案

If you're looking to get rid of consecutive duplicates only, this should suffice:

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

Details

\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

Regex from here.

To remove non-consecutive duplicates, I'd suggest a solution involving the OrderedDict data structure:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值