使用python脚本从csv文件中删除重复行

使用python脚本从csv文件中删除重复行,python,file-io,Python,File Io,目标 我从hotmail下载了一个CSV文件,但其中有很多重复项。这些副本是完整的副本,我不知道为什么我的手机会创建它们 我想把复制品处理掉 方法 编写python脚本以删除重复项 技术规范 Windows XP SP 3 Python 2.7 CSV file with 400 contacts Windows XP SP 3 Python 2.7 包含400个联系人的CSV文件 您可以使用以下脚本: 先决条件: 1.csv是包含重复项的文件 2.csv是执行此脚本后将没有重复项的输出文件 代

目标

我从hotmail下载了一个CSV文件,但其中有很多重复项。这些副本是完整的副本,我不知道为什么我的手机会创建它们

我想把复制品处理掉

方法

编写python脚本以删除重复项

技术规范

Windows XP SP 3 Python 2.7 CSV file with 400 contacts Windows XP SP 3 Python 2.7 包含400个联系人的CSV文件
您可以使用以下脚本:

先决条件:

  • 1.csv
    是包含重复项的文件
  • 2.csv
    是执行此脚本后将没有重复项的输出文件
  • 代码

    
    
    inFile = open('1.csv','r')
    
    outFile = open('2.csv','w')
    
    listLines = []
    
    for line in inFile:
    
        if line in listLines:
            continue
    
        else:
            outFile.write(line)
            listLines.append(line)
    
    outFile.close()
    
    inFile.close()
    
    
    infle=open('1.csv','r')
    outFile=open('2.csv','w')
    列表行=[]
    对于填充中的线:
    如果列表行中有行:
    持续
    其他:
    输出文件。写入(行)
    追加(行)
    outFile.close()
    infle.close()
    

    算法说明

    Windows XP SP 3 Python 2.7 CSV file with 400 contacts 在这里,我正在做的是:

  • 以读取模式打开文件。这是包含重复项的文件
  • 然后在一个循环中运行,直到文件结束,我们检查行 已经遇到了
  • 如果遇到它,我们不会将其写入输出文件
  • 如果没有,我们将把它写入输出文件,并将其添加到已经遇到的记录列表中

  • 更新:2016

    如果您愿意使用有用的外部库:

    from more_itertools import unique_everseen
    with open('1.csv','r') as f, open('2.csv','w') as out_file:
        out_file.writelines(unique_everseen(f))
    


    @IcyFlame解决方案的更高效版本

    with open('1.csv','r') as in_file, open('2.csv','w') as out_file:
        seen = set() # set for fast O(1) amortized lookup
        for line in in_file:
            if line in seen: continue # skip duplicate
    
            seen.add(line)
            out_file.write(line)
    
    要在位编辑同一文件,可以使用以下命令

    import fileinput
    seen = set() # set for fast O(1) amortized lookup
    for line in fileinput.FileInput('1.csv', inplace=1):
        if line in seen: continue # skip duplicate
    
        seen.add(line)
        print line, # standard output is now redirected to the file
    
    import fileinput
    seen = set() # set for fast O(1) amortized lookup
    for line in fileinput.FileInput('1.csv', inplace=1):
        if line not in seen:
            seen.add(line)
            print line, # standard output is now redirected to the file   
    

    @jamylak解决方案的更有效版本:(只需一条指令)

    要在位编辑同一文件,可以使用以下命令

    import fileinput
    seen = set() # set for fast O(1) amortized lookup
    for line in fileinput.FileInput('1.csv', inplace=1):
        if line in seen: continue # skip duplicate
    
        seen.add(line)
        print line, # standard output is now redirected to the file
    
    import fileinput
    seen = set() # set for fast O(1) amortized lookup
    for line in fileinput.FileInput('1.csv', inplace=1):
        if line not in seen:
            seen.add(line)
            print line, # standard output is now redirected to the file   
    

    您可以使用Pandas高效地实现重复数据传输, 安装熊猫使用

    pip install pandas
    
    代码

    import pandas as pd
    file_name = "my_file_with_dupes.csv"
    file_name_output = "my_file_without_dupes.csv"
    
    df = pd.read_csv(file_name, sep="\t or ,")
    
    # Notes:
    # - the `subset=None` means that every column is used 
    #    to determine if two rows are different; to change that specify
    #    the columns as an array
    # - the `inplace=True` means that the data structure is changed and
    #   the duplicate rows are gone  
    df.drop_duplicates(subset=None, inplace=True)
    
    # Write the results to a different file
    df.to_csv(file_name_output, index=False)
    

    您可以在jupyter笔记本或相关IDE中使用熊猫库,我正在将熊猫导入jupyter笔记本并读取csv文件

    然后对这些值进行排序,根据这些值重复出现的参数,因为我已经定义了两个属性,它将首先按时间排序,然后按纬度排序

    然后根据需要删除时间列或相关列中的重复项

    然后,我将删除并排序的重复文件存储为gps_排序

    import pandas as pd
    stock=pd.read_csv("C:/Users/Donuts/GPS Trajectory/go_track_trackspoints.csv")
    stock2=stock.sort_values(["time","latitude"],ascending=True)
    stock2.drop_duplicates(subset=['time'])
    stock2.to_csv("C:/Users/Donuts/gps_sorted.csv",)
    

    希望这能有所帮助

    我知道这个问题早已解决,但我遇到了一个密切相关的问题,即我要基于一列删除重复项。输入的csv文件相当大,可以通过MS Excel/Libre Office Calc/Google Sheets在我的电脑上打开147MB,约有250万条记录。因为我不想为这么简单的事情安装整个外部库,所以我编写了下面的python脚本,以便在不到5分钟的时间内完成这项工作。我没有把重点放在优化上,但我相信它可以被优化,以便在更大的文件中运行得更快、更高效。该算法类似于上面的@IcyFlame,只是我基于一列(“CCC”)而不是整行/行删除重复项

    import csv
    
    with open('results.csv', 'r') as infile, open('unique_ccc.csv', 'a') as outfile:
        # this list will hold unique ccc numbers,
        ccc_numbers = []
        # read input file into a dictionary, there were some null bytes in the infile
        results = csv.DictReader(infile)
        writer = csv.writer(outfile)
    
        # write column headers to output file
        writer.writerow(
            ['ID', 'CCC', 'MFLCode', 'DateCollected', 'DateTested', 'Result', 'Justification']
        )
        for result in results:
            ccc_number = result.get('CCC')
            # if value already exists in the list, skip writing it whole row to output file
            if ccc_number in ccc_numbers:
                continue
            writer.writerow([
                result.get('ID'),
                ccc_number,
                result.get('MFLCode'),
                result.get('datecollected'),
                result.get('DateTested'),
                result.get('Result'),
                result.get('Justification')
            ])
    
            # add the value to the list to so as to be skipped subsequently
            ccc_numbers.append(ccc_number)
    

    当试图打开我的文件时,我得到
    UnicodeDecodeError:“utf-8”编解码器无法解码第28位的字节0x96:无效的开始字节file@ykombinator您可以将“encoding”参数传递给“read\u csv”函数——请参阅df.to\u csv(文件名\u输出,索引=False)坦率地说,我不知道为什么要用fileinput打开文件,将内容还原回一个冻结集。fileinput应该用于编辑您打开的文件,而您的示例中没有这样做。我不会使用Pandas进行此类操作,因为根据文件大小,I/O操作可能会产生性能问题。