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

Python 比较两个csv文件的多列,并将输出另存为新csv文件中的匹配/不匹配,python,pandas,csv,dictionary,comparison,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

假设我在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获得上述输出

另外,除了列名,比较多列的代码是什么

我的代码

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

这很好,但是我可以用任何其他更简单的方法来获得相同的输出吗?我需要做哪些更改来比较多个列

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

将两个csv文件读入两个不同的词典,并在其中任何一个词典上迭代,然后在另一个词典中检查相同的密钥。如果您想订购,请使用OrderedDict

如果您不介意使用Pandas,您可以使用5行代码:

将熊猫作为pd导入
#假设id列相同并且包含相同的值
df1=pd.read\u csv('file1.csv',index\u col='Customer\u id'))
df2=pd.read\u csv('file2.csv',index\u col='Customer\u id'))
df3=pd.DataFrame(列=['status'],索引=df1.index)
df3['status']=(df1['Name']==df2['Name'])。替换([True,False],'Matching','notmatching'])
df3.to_csv('output.csv'))

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

如果您不介意使用熊猫,您可以在5行代码中完成此操作:

将熊猫作为pd导入
#假设id列相同并且包含相同的值
df1=pd.read\u csv('file1.csv',index\u col='Customer\u id'))
df2=pd.read\u csv('file2.csv',index\u col='Customer\u id'))
df3=pd.DataFrame(列=['status'],索引=df1.index)
df3['status']=(df1['Name']==df2['Name'])。替换([True,False],'Matching','notmatching'])
df3.to_csv('output.csv'))
编辑:已删除
sep='\t'
以使用默认逗号分隔符。

您可以在多个列上:

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
您可以在多个列上执行以下操作:

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


到目前为止你试过什么?使用winmerge之类的字符串比较工具怎么样?类似的问题和@蕭為元 你可以看到我试过的代码。我已经编辑了这个问题,你能用熊猫吗?@Sreeram是的,当然,到目前为止你试过什么?使用winmerge之类的字符串比较工具怎么样?类似的问题和@蕭為元 你可以看到我试过的代码。我已经编辑了这个问题,你能用熊猫吗?@Sreeram是的,当然是Python脚本@Sanjay的Python脚本@Sanjay Idpuganti@Alex,这不会产生所需的输出,否则很容易:)@pytorch我已经更新了一点代码,使其更短/更易于维护。@Alex,这不会产生所需的输出,否则很容易:)@pytorch我已经更新了一点代码,使其更短/更易于维护。我得到了ValueError:Index Customer\u id无效。但是将sep='\t'更改为sep=','解决了错误抱歉,我的错!如果使用逗号分隔的值/I Get ValueError:Index Customer_id invalid,则实际上可以完全忽略分隔符参数。但是将sep='\t'更改为sep=','解决了错误抱歉,我的错!如果使用逗号分隔的值,实际上可以完全忽略分隔符参数/