删除熊猫同一行中的重复单词

时间:2020-07-24 15:52:41

标签: python pandas

我对Python Pandas和编程很陌生。我有一个看起来像这样的数据框(只是一个简化的示例):

   A      B  
0  name1  Dog, Dog, Cat
1  name2  Dog, Bird
2  name3  Cat, Cat, Cat
3  name4  Dog, Cat, Bird

我想删除每一行上重复的值,所以我的DataFrame看起来像这样:

       A      B  
0  name1  Dog, Cat
1  name2  Dog, Bird
2  name3  Cat
3  name4  Dog, Cat, Bird

我看到我可以用from collections import OrderedDict做类似的事情,但是正如我所说的,我对编程还很陌生,我也不知道该怎么做。如果您能帮助我,那太好了,谢谢!

1 个答案:

答案 0 :(得分:2)

使用applyjoin

df['B'] = df['B'].apply(lambda x: ', '.join(set(x.split(', '))))

print(df)
       A               B
0  name1        Dog, Cat
1  name2       Dog, Bird
2  name3             Cat
3  name4  Dog, Cat, Bird