对具有不同列的多个CSV文件中的记录进行重复数据消除

2024-05-19 14:00:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个目录中有多个CSV文件。有些包含更多的列(可以删除)。在

有没有一种优雅的方法可以消除这些CSV文件之间的重复记录,并将列缩减为一组常见的列?在

目前,我将使用python/pandas来实现这一点。我将把所有文件加载到一个单独的数据帧中,在记录的来源(filename)的附加列中注意,删除附加的列,最后通过http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html对pandas进行重复数据消除 根据上一个已消除重复的文件名,将文件名写回步骤I中的最后一个已删除的文件名。在

# ASSUMPTION: files are in order, first file defines minimum common columns
path = '.'
files_in_dir = [f for f in os.listdir(path)if f.endswith('csv')] 
isFirst = True

for filenames in fs.find('*.csv', path):
    df = pd.read_csv(filenames, error_bad_lines=False)
    df['origin'] = fs.add_suffix(filenames, '_deduplicated')
    if (isFirst):
        isFirst = False
        bigDf = df
    else:
        bigDf = pd.concat(bigDf, df, axis=0, join='inner')
cols_for_dup = [col for col in bigDf.columns if col not in ['origin']]
bigDf.duplicated(subset=cols_for_dup).sum()
bigDf.duplicated().sum()
bigDf_withoutNA = bigDf.drop_duplicates(keep='first', subset= cols_for_dup)

grouped = bigDf_withoutNA.groupby('origin')
for name, group in grouped:
    #filename = 'path' + name
    group.to_csv(path_or_buf= name, sep=';', decimal=',')

有没有更简单的方法?在


Tags: 文件csvpathinpandasdfforif
1条回答
网友
1楼 · 发布于 2024-05-19 14:00:09

我不知道如何使它更简单。我对我的一些数据做了同样的脚本。它只运行两次,首先确定所有文档中的最小/最大列数,最后将csv文件重写到一个新文件夹中,以保留原始数据。在

我只是使用python的csv库。 https://docs.python.org/2/library/csv.html

这个脚本没有检查,因为它只是一个快速而肮脏的脚本。在

重复数据消除未完成。它只是将所有数据缩减到相同的长度,但您可以用重复数据消除代码替换最后一行。在

import os
import csv

mincols = 0xffffffff
maxcols = 0

srcdir = '/tmp/csv/'
dstdir = '/tmp/csv2/'

for dirName, subdirList, fileList in os.walk(srcdir):
    for fname in fileList:
        if fname[-4:].lower() == '.csv':
            with open(os.path.join(dirName, fname)) as csvfile:
                reader = csv.reader(csvfile, delimiter=',', quotechar='"')
                for row in reader:
                    if mincols > len(row):
                        mincols = len(row)
                    if maxcols < len(row):
                        maxcols = len(row)

print(mincols, maxcols)

for dirName, subdirList, fileList in os.walk(srcdir):
    for fname in fileList:
        if fname[-4:].lower() == '.csv':
            fullpath = os.path.join(dirName, fname)    
            newfile = os.path.join(dstdir, fullpath[len(srcdir):])

            if not os.path.exists(os.path.dirname(newfile)):
                os.makedirs(os.path.dirname(newfile))
            with open(fullpath) as csvfile:
                reader = csv.reader(csvfile, delimiter=',', quotechar='"')
                with open(newfile, 'w') as dstfile:
                    writer = csv.writer(dstfile, delimiter=',', quotechar='"',
                        quoting=csv.QUOTE_MINIMAL)
                    for row in reader:
                        #You can deduplicate here 
                        writer.writerow(row[:mincols])                  

相关问题 更多 >