首页 > 解决方案 > 如何在python中删除csv行中的重复单词?

问题描述

我正在使用 csv 文件,我有很多行包含重复的单词,我想删除任何重复项(我也不想丢失句子的顺序)。

csv 文件示例(用户 ID 和描述是列名):

userID, description

12, hello world hello world

13, I will keep the 2000 followers same I will keep the 2000 followers same

14, I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car

.

.

我希望输出为:

userID, description

12, hello world 

13, I will keep the 2000 followers same

14, I paid $2000 to the car 

.

.

我已经尝试过诸如1 2 3之类的帖子,但它们都没有解决我的问题,也没有改变任何东西。(我的输出文件的顺序很重要,因为我不想丢失订单)。如果你能提供一个代码示例,我可以在我身边运行并学习,那就太好了。谢谢

【我用的是python 3.7版本】

标签: pythonpandascsvdataframe

解决方案


要删除重复项,我建议使用一个涉及 OrderedDict 数据结构的解决方案:

df['Desired'] = (df['Current'].str.split()
                          .apply(lambda x: OrderedDict.fromkeys(x).keys())
                          .str.join(' '))

推荐阅读