首页 > 解决方案 > 比较两个 csv 文件的多列并将输出保存为新 csv 文件中的匹配/不匹配

问题描述

假设我在 file1.csv 中有列

Customer id    Name 

Q1             Alen
W2             Ricky
E3             Katrina
R4             Anya
T5             Leonardo

和 file2.csv 中的列为

Customer id    Name

Q1             Alen
W2             Harry
E3             Katrina
R4             Anya
T5             Leonard

在这里,您可以看到 Customer id: W2 对应的名称不匹配。所以 output.csv 应该如下所示:

Customer id  Status

Q1           Matching
W2           Not matching
E3           Matching
R4           Matching
T5           Matching

如何使用 python 获得上述输出。

PS什么是比较多列的代码,而不仅仅是列名?

我的代码

import csv
with open('file1.csv', 'rt', encoding='utf-8') as csvfile1:
    csvfile1_indices = dict((r[1], i) for i, r in enumerate(csv.reader(csvfile1)))

with open('file2.csv', 'rt', encoding='utf-8') as csvfile2:
    with open('output.csv', 'w') as results:    
        reader = csv.reader(csvfile2)
        writer = csv.writer(results)

        writer.writerow(next(reader, []) + ['status'])

        for row in reader:
            index = csvfile1_indices.get(row[1])
            if index is not None:
                message = 'matching'
                writer.writerow(row + [message])

            else:
                 message = 'not matching'
                 writer.writerow(row + [message])

    results.close()

这工作正常,但我可以用任何其他更简单的方式编写以获得相同的输出吗?我需要进行哪些更改来比较多个列?

标签: pythonpandascsvdictionarycomparison

解决方案


如果你不介意使用 Pandas,你可以用 5 行代码来完成:

import pandas as pd 

# assuming id columns are identical and contain the same values
df1 = pd.read_csv('file1.csv', index_col='Customer_id')
df2 = pd.read_csv('file2.csv', index_col='Customer_id')

df3 = pd.DataFrame(columns=['status'], index=df1.index)
df3['status'] = (df1['Name'] == df2['Name']).replace([True, False], ['Matching', 'Not Matching'])

df3.to_csv('output.csv')

编辑:删除sep = '\t'以使用默认逗号分隔符。


推荐阅读