【问题标题】:Performance improvement when comparing 2 huge csv files [python]比较 2 个巨大的 csv 文件时的性能改进 [python]
【发布时间】:2016-10-31 14:15:26
【问题描述】:

我有 2 个 csv 文件,我需要针对另一个文件中的所有行测试第一个文件中的每一行,并将匹配的行写入一个新的 csv 文件。这是文件结构。

csv 1(读数间隔 20 秒采样。第一行始终是标题):

日期时间 Col1 Col2
2016 年 6 月 27 日 17:28:21 21 3244
2016 年 6 月 27 日 17:28:41 21 3278
2016 年 6 月 27 日 17:29:01 21 3299

csv 2(读数间隔为 1 秒。无标题):

2016 年 6 月 27 日 17:28:21 3245
2016 年 6 月 27 日 17:28:22 3266
2016 年 6 月 27 日 17:28:23 3277

我比较来自 csv1 和 csv2 的时间戳,并在匹配时创建一个输出行,其中包含 csv1 行加上从 csv2 读取的第二列。输出 csv 文件中的示例行将是:

日期时间 Col1 Col2 Col3
2016 年 6 月 27 日 17:28:21 21 3244 3245

这是我的python代码:

    with open("file1.csv",'r') as csv1:  
             with open("out.csv", 'w') as myoutput:
             writer = csv.writer(myoutput)
             row_count=0
             headerSet=0
             for row in csv.reader(csv1):
                 with open ("file2.csv",'r') as csv2:
                     in2 = csv.reader(csv2)
                     for mrow in in2:
                        if row_count == 0 and headerSet==0:
                            # Generate Header Row for the output csv file
                            writer.writerow(row+["Col3"]) 
                            headerSet=1
                        else:
                            # Code to fetch timestamp from csv1 and csv2
                            if csv1_ts == csv2_ts:
                                # Fetch 2nd column value from csv2
                                val=mrow[1]
                                writer.writerow(row+[val])
                                break
                     else:
                        continue
                     row_count += 1

代码似乎需要花费大量时间来生成输出 csv 文件。我可以做些什么来提高这段代码的性能并加快它的速度?

【问题讨论】:

    标签: python loops csv


    【解决方案1】:

    由于行似乎是按时间排序的,因此您最初可以从两个文件中读取一行。如果行的时间戳匹配,则将该行写入输出并前进到两个文件中的下一行。如果时间戳不同,则从当前时间戳较小的文件中读取下一行。下面是实际代码的简单实现:

    import csv
    
    def get_key(row):
        date = [int(x) for x in row[0].split('/')]
        date[0], date[2] = date[2], date[0]
        return date, row[1]
    
    with open('file1.csv') as csv1, open('file2.csv') as csv2, open('out.csv', 'w') as out:
        csv1 = csv.reader(csv1)
        csv2 = csv.reader(csv2)
        out = csv.writer(out)
    
        # Header
        out.writerow(next(csv1) + ['Col3'])
        row1 = next(csv1, None)
        row2 = next(csv2, None)
    
        while row1 and row2:
            key1 = get_key(row1)
            key2 = get_key(row2)
            if key1 < key2:
                row1 = next(csv1, None)
            elif key1 > key2:
                row2 = next(csv2, None)
            else:
                out.writerow(row1 + row2[-1:])
                row1 = next(csv1, None)
                row2 = next(csv2, None)
    

    【讨论】:

    • 像魅力一样工作
    猜你喜欢
    • 1970-01-01
    • 2020-09-18
    • 2017-11-10
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多