如何在python的csv行中删除重复的单词?

时间:2019-05-27 20:36:08

标签: python pandas csv dataframe

我正在使用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版本]

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

以下代码对我有用:

a = pd.Series(["hello world hello world", 
               "I will keep the 2000 followers same I will keep the 2000 followers same",
               "I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car"])
a.apply(lambda x: " ".join([w for i, w in enumerate(x.split()) if x.split().index(w) == i]))

基本上,对于每个单词,只有在其位置在列表中的第一个位置时才保留它(使用空格从字符串中拆分出来)。这意味着,如果单词第二次(或更多次)出现,则.index()函数将返回小于当前出现位置的索引,从而将其消除。

这将为您提供:

0                            hello world
1    I will keep the 2000 followers same
2                I paid $2000 to the car
dtype: object

答案 2 :(得分:0)

解决方案取自here

def principal_period(s):
    i = (s+s).find(s, 1)
    return s[:i]

df['description'].apply(principal_period)

输出:

0                                 hello world
1     I will keep the 2000 followers the same
2                     I paid $2000 to the car
Name: description, dtype: object

由于此方法在字符串上使用apply,因此速度可能很慢。

答案 3 :(得分:0)

取自How can I tell if a string repeats itself in Python?

的答案
import pandas as pd
def principal_period(s):
    s+=' '
    i = (s + s).find(s, 1, -1)
    return None if i == -1 else s[:i]
df=pd.read_csv(r'path\to\filename_in.csv')
df['description'].apply(principal_period)
df.to_csv(r'output\path\filename_out.csv')

说明:

我在末尾添加了一个空格,以确保重复的字符串由空格分隔。然后,在将字符串添加到自身时,查找第二个出现的字符串(分别减去第一个和最后一个字符,以避免首先匹配,并且在没有重复字符串的情况下分别查找最后一个)。这样可以有效地找到第二个出现的字符串开始或第一个最短的重复字符串结束的字符串位置。然后返回此重复字符串。