python - 比较两个 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()
这工作正常,但我可以用任何其他更简单的方式编写以获得相同的输出吗?我需要进行哪些更改来比较多个列?
解决方案
如果你不介意使用 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'
以使用默认逗号分隔符。
推荐阅读
- c# - Apple 支付抑制 - 我做错了什么?
- javascript - 获取货币值作为数字
- python - 使用 JAX 进行梯度累积
- firebase - 使用 firebase 在 React Native 中编辑和更新图像
- go - js 客户端连接到 go-socket.io 服务器,但得到重复重新连接
- python - 点云内的open3d高亮点
- string - 在 Fortran 中,空字符串和未初始化的字符串有什么区别?
- javascript - React Native GiftedChat 消息排序
- c++ - c++方法不改变对象字段,是标准容器
- matlab - Matlab PointCloud 处理排列