删除非常大的数据集上的重复项

Vla*_*lad 10 python duplicates large-data

我正在研究一个包含大约1600万行和85列的13.9 GB csv文件.我知道可能有几十万行是重复的.我运行此代码来删除它们

import pandas

concatDf=pandas.read_csv("C:\\OUT\\Concat EPC3.csv")
nodupl=concatDf.drop_duplicates()
nodupl.to_csv("C:\\OUT\\Concat EPC3- NoDupl.csv",index=0)
low_memory=False  
Run Code Online (Sandbox Code Playgroud)

然而,这让我陷入了MemoryError.我的公羊是16克,不能再高了.是否有一种更有效的方法来删除重复项,如果没有我不得不将csv文件分解为更小的文件?

jde*_*esa 10

本质上与zwer相同,但检查具有相同哈希的行是否相等(而不是自动丢弃重复的哈希)。

file_in = "C:\\OUT\\Concat EPC3.csv"
file_out = "C:\\OUT\\Concat EPC3- NoDupl.csv"

with open(file_in, 'r') as f_in, open(file_out, 'w') as f_out:
    # Skip header
    next(f_in)
    # Find duplicated hashes
    hashes = set()
    hashes_dup = {}
    for row in f_in:
        h = hash(row)
        if h in hashes:
            hashes_dup[h] = set()
        else:
            hashes.add(h)
    del hashes
    # Rewind file
    f_in.seek(0)
    # Copy header
    f_out.write(next(f_in))
    # Copy non repeated lines
    for row in f_in:
        h = hash(row)
        if h in hashes_dup:
            dups = hashes_dup[h]
            if row in dups:
                continue
            dups.add(row)
        f_out.write(row)
Run Code Online (Sandbox Code Playgroud)


zwe*_*wer 5

最简单的解决方案是为文件中的每一行创建一个哈希表 - 在你的工作内存中存储16M哈希应该不是问题(取决于哈希大小,你) - 然后你可以再次迭代你的文件并确保你只记下每个哈希的一次出现.您甚至不需要解析CSV也不需要Pandas.

import hashlib

with open("input.csv", "r") as f_in, \
        open("output.csv", "w") as f_out:
    seen = set()  # a set to hold our 'visited' lines
    for line in f_in:  # iterate over the input file line by line
        line_hash = hashlib.md5(line.encode()).digest()  # hash the value
        if line_hash not in seen:  # we're seeing this line for the first time
            seen.add(line_hash)  # add it to the hash table
            f_out.write(line)  # write the line to the output
Run Code Online (Sandbox Code Playgroud)

这使用MD5作为哈希,因此每行需要大约16B +设置开销,但这仍然远远少于将所有内容存储在内存中 - 对于16M行CSV文件,您可以预期大约500MB的内存使用量.