gpt4 book ai didi

python - 如何在 Python 中比较两个 CSV 文件?

转载 作者:行者123 更新时间:2023-12-05 03:39:26 32 4
gpt4 key购买 nike

我在 file2.csv 中有两个 CSV 文件,分别命名为 file1.csvfile2.csv只有一列只包含五个记录,在 file1.csv 我有三列包含超过一千条记录 我想获取 file2.csv 例如,这是我的 file1.csv

'A J1, Jhon1',jhon1@jhon.com, A/B-201 Test1
'A J2, Jhon2',jhon2@jhon.com, A/B-202 Test2
'A J3, Jhon3',jhon3@jhon.com, A/B-203 Test3
'A J4, Jhon4',jhon4@jhon.com, A/B-204 Test4
.......and more records

在我的 file2.csv 我现在只有五个记录,但将来可能会很多

A/B-201 Test1
A/B-2012 Test12
A/B-203 Test3
A/B-2022 Test22

所以我必须在 index[2]index[-1] 处从我的 file1.csv 中查找记录

这就是我所做的,但它没有给我任何输出,它只是返回空列表

import csv 

file1 = open('file1.csv','r')
file2 = open('file2.csv','r')

f1 = list(csv.reader(file1))
f2 = list(csv.reader(file2))


new_list = []

for i in f1:
if i[-1] in f2:
new_list.append(i)

print('New List : ',new_list)

它给我这样的输出

New List :  []

如果我做错了什么,请帮助纠正我。

最佳答案

方法一:pandas

使用 pandas 可以相对轻松地完成此任务。 DataFrame documentation here .

示例:

在下面的示例中,两个 CSV 文件被读入两个 DataFrame。使用匹配列上的内部联接合并 DataFrame。

输出显示合并结果。

import pandas as pd

df1 = pd.read_csv('file1.csv', names=['col1', 'col2', 'col3'], quotechar="'", skipinitialspace=True)
df2 = pd.read_csv('file2.csv', names=['match'])

df = pd.merge(df1, df2, left_on=df1['col3'], right_on=df2['match'], how='inner')

quotecharskipinitialspace 参数用作 file1 中的第一列被引用并包含一个逗号,并且后面有前导空格最后一个字段前的逗号。

输出:

    col1            col2            col3
0 A J1, Jhon1 jhon1@jhon.com A/B-201 Test1
1 A J3, Jhon3 jhon3@jhon.com A/B-203 Test3

如果您选择,输出可以很容易地写回 CSV 文件,如下所示:

df.to_csv('path/to/output.csv')

对于其他 DataFrame 操作,请参阅上面链接的文档。


方法二:核心Python

下面的方法不使用任何库,只使用核心 Python。

  1. file2 中的匹配项读入列表。
  2. 遍历 file1 并搜索每一行以确定最后一个值是否与 file2 中的项目匹配。
  3. 报告输出。

任何后续数据清理(如果需要)将取决于您的个人要求或用例。

示例:

output = []

# Read the matching values into a list.
with open('file2.csv') as f:
matches = [i.strip() for i in f]

# Iterate over file1 and place any matches into the output.
with open('file1.csv') as f:
for i in f:
match = i.split(',')[-1].strip()
if any(match == j for j in matches):
output.append(i)

输出:

["'A J1, Jhon1',jhon1@jhon.com, A/B-201 Test1\n",
"'A J3, Jhon3',jhon3@jhon.com, A/B-203 Test3\n"]

关于python - 如何在 Python 中比较两个 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68572896/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com