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

安吉蒂瓦里

file2.csv 中两个名为file1.csvfile2.csv 的CSV文件,只有一列仅包含五条记录,而在file1.csv 中,我有三列包含超过一千条记录我想得到那些包含在file2.csv 中的记录例如这是我的file1.csv

'A J1, Jhon1',[email protected], A/B-201 Test1
'A J2, Jhon2',[email protected], A/B-202 Test2
'A J3, Jhon3',[email protected], A/B-203 Test3
'A J4, Jhon4',[email protected], 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

所以我必须从我的file1.csvat index[2]index[-1] 中找到记录

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

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 :  []

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

S3DEV

方法一: pandas

使用 可以相对轻松地完成此任务pandas此处为 DataFrame 文档

例子:

在下面的示例中,两个 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     [email protected]  A/B-201 Test1
1   A J3, Jhon3     [email protected]  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',[email protected], A/B-201 Test1\n",
 "'A J3, Jhon3',[email protected], A/B-203 Test3\n"]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章