比较两个csv文件的多列并将输出保存为匹配/不匹配的新csv文件

时间:2018-11-05 09:42:33

标签: python pandas csv dictionary comparison

假设我的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

在这里您可以看到客户ID:W2,相应的名称不匹配。因此output.csv应该如下所示:

Customer id  Status

Q1           Matching
W2           Not matching
E3           Matching
R4           Matching
T5           Matching

如何使用python获取以上输出。

P.S。比较多个列而不只是列名的代码是什么?

我的代码

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()

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

3 个答案:

答案 0 :(得分:1)

如果您不介意使用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'以使用默认的逗号分隔符。

答案 1 :(得分:0)

将两个csv文件读入两个不同的字典中,并遍历任何词典,然后在另一个词典中检查相同的键。如果要订购,请使用OrderedDict

答案 2 :(得分:0)

您可以在多列上merge

f1
  Customer_id      Name
0          Q1      Alen
1          W2     Ricky
2          E3   Katrina
3          R4      Anya
4          T5  Leonardo

f2
  Customer_id      Name
0          Q1      Alen
1          W2     Harry
2          E3   Katrina
3          R4      Anya
4          T5  Leonardo

m = f1.merge(f2, on=['Customer_id', 'Name'], indicator='Status', how='outer')
  Customer_id      Name      Status
0          Q1      Alen        both
1          W2     Ricky   left_only
2          E3   Katrina        both
3          R4      Anya        both
4          T5  Leonardo        both
5          W2     Harry  right_only

m['Status'] = m['Status'].map({'both': 'Matching', 
                               'left_only': 'Not matching', 
                               'right_only': 'Not matching'})

m.drop_duplicates(subset=['Customer_id', 'Status'])
m.drop(['Name'], axis=1)
  Customer_id        Status
0          Q1      Matching
1          W2  Not matching
2          E3      Matching
3          R4      Matching
4          T5      Matching
相关问题