簡體   English   中英

如何在 Python 中比較兩個 CSV 文件?

[英]How to compare two CSV files in Python?

我在file2.csv中有兩個名為file1.csvfile2.csvCSV文件,只有一列只包含五條記錄,而在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 文檔在這里

例子:

在下面的示例中,兩個 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 操作,請參閱上面鏈接的文檔。


方法2:核心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"]
  1. 使用集合或字典in檢查(復雜度為 O(1),而不是 O(N) 用於列表和元組)。
  2. 看看convtools庫( github ):它有Table helper 用於處理表數據和流( table docs
from convtools import conversion as c
from convtools.contrib.tables import Table

# creating a set of allowed values
allowed_values = {
    item[0] for item in Table.from_csv("input2.csv").into_iter_rows(tuple)
}

result = list(
    # reading a file with custom quotechar
    Table.from_csv("input.csv", dialect=Table.csv_dialect(quotechar="'"))
    # stripping last column values
    .update(COLUMN_2=c.col("COLUMN_2").call_method("strip"))
    # filtering based on allowed values
    .filter(c.col("COLUMN_2").in_(c.naive(allowed_values)))
    # returning iterable of tuples
    .into_iter_rows(tuple)

    # # OR outputting csv if needed
    # .into_csv("result.csv")
)
"""
>>> In [36]: result
>>> Out[36]:
>>> [('A J1, Jhon1', 'jhon1@jhon.com', 'A/B-201 Test1'),
>>>  ('A J3, Jhon3', 'jhon3@jhon.com', 'A/B-203 Test3')]
"""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM