繁体   English   中英

比较csv文件中的两列

[英]Compare two columns in csv files

two csv files ,第first文件third column有一定数量的data行, second file first column有类似的数据,也有一些不确定的数量,这些以md5的形式呈现,对于例子:

文件_1

列_1 列_2 第 3 列
等等等等等等 等等等等等等 aa7744226c695c0b2e440419848cf700
等等等等等等 等等等等等等 9b34939b137e24f8c6603a54b2305f07
等等等等等等 等等等等等等 ad1172b28f277eab7ca91f96f13a242b
etc

文件_2

列_1 列_2 第 3 列
49269f413284abfa58f41687b6f631e0 等等等等等等 等等等等等等
a0879ff97178e03eb18470277fbc7056 等等等等等等 等等等等等等
9e5b91c360d6be29d556db7e1241ce82 等等等等等等 等等等等等等
etc

你能告诉我,我如何比较两个文件中的这两列,即找到duplicate值,如果这些值重复,则显示第一个和第二个csv file

我试图从这个例子中得到一些东西:

import csv    
interesting_cols = [0, 2, 3, 4, 5]    
with open("/root/file1.csv", 'r') as file1,\
     open("/root/file2.csv", 'r') as file2:    
    reader1, reader2 = csv.reader(file1), csv.reader(file2)    
    for line1, line2 in zip(reader1, reader2):
        equal = all(x == y for n, (x, y) in enumerate(zip(line1, line2)) if n in interesting_cols)
        print(equal)

如果两个文件每个只有一列,则此示例将运行良好。 根据我的要求,我无法以任何方式实现它,我的Python非常薄弱。 非常感谢!

如果你被允许,你可以使用 Pandas 来做到这一点。 首先使用 pip 安装包: python -m pip install pandas

或 conda: conda install pandas

然后阅读并与熊猫进行比较:

import pandas as pd
interesting_cols = [0, 2, 3, 4, 5]    
file1 = pd.read_csv("/root/file1.csv")
file2 = pd.read_csv("/root/file2.csv")
comp = file1.compare(file2)
print(comp.to_markdown())

或者,如果您希望保留 'with' 语句,您应该创建一个类并定义__enter____exit__方法:

import pandas as pd
interesting_cols = [0, 2, 3, 4, 5]    
class DataCSV:
    def __init__(self, file) -> None:
        self.filename = file
    def __enter__(self):
        self.file = pd.read_csv(self.filename)
        return self.file
    def __exit__(self, exc_type, exc_value, traceback):
        pass
with DataCSV("/root/file1.csv") as file1, DataCSV("/root/file2.csv") as file2:
    comp = file1.compare(file2)
    print(comp.to_markdown())

输出应该是这样的:

('column_1', '自我') ('column_1', '其他') ('column_3', '自我') ('column_3', '其他')
0 等等等等等等 49269f413284abfa58f41687b6f631e0 aa7744226c695c0b2e440419848cf700 等等等等等等
1 等等等等等等 a0879ff97178e03eb18470277fbc7056 9b34939b137e24f8c6603a54b2305f07 等等等等等等
2 等等等等等等 9e5b91c360d6be29d556db7e1241ce82 ad1172b28f277eab7ca91f96f13a242b 等等等等等等

您可以重新排序列表并使用生成器快速检查它。

import csv

def parse_csv(filename, header=False, delim=',', quotechar='"'):
    with open(filename, 'r') as f:
        csvfile = csv.reader(f, delimiter=delim, quotechar=quotechar)
        if header:
            csvfile.__next__()
        for row in csvfile:
            yield row

def diff(l1, l2, reorder=None):
    if reorder:
        for i,line in enumerate(l2):
            l2[i] = [line[x] for x in line]
    for i, line in enumerate(l1):
        if line not in l2:
            yield i,  line

filename1 = ''
filename2 = ''
reorder = [2,1,0]

missing = [(i, line) for i,line in diff(parse_csv(filename1, header=False), list(parse_csv(filename2, header=False)), reorder=reorder) or (None, None)]
print(missing)

在这里,它说从 csv 文件读取的每一行都作为字符串列表返回。 您可以从这些行中读取单个列。

例如:

使用两个简单的 csv 文件
地址.csv

Doe,John,120 jefferson st.,Riverside, NJ, 08075
McGinnis,Jack,220 hobo Av.,Phila, PA,09119
Repici,"John ""Da Man""",120 Jefferson St.,Riverside, NJ,08075
Tyler,Stephen,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234

电话.csv

John,Doe,19122
Jack,McGinnis,20220
"John ""Da Man""",Repici,1202134
Stephen,Tyler,72384


>>> with open('addresses.csv') as file1, open('phones.csv') as file2:
...     r1, r2 = csv.reader(file1), csv.reader(file2)
...     for line1, line2 in zip(r1, r2):
...             if line1[1] == line2[0]:
...                     print('found a duplicate', line1[1])
...
found a duplicate John
found a duplicate Jack
found a duplicate John "Da Man"
found a duplicate Stephen

我们得到在指定列中具有相同值的行。 在我们的例子中,这些是第一个 csv 文件的第二列和第二个 csv 文件的第一列。 为了获取行号,您可以像您提供的示例代码一样使用enumerate(zip())

您可以检查Python 列表推导式以了解示例中使用的语法。

我的答案将适用于 files 中的所有记录 它将在 file1 和 file2 中的所有记录中找到匹配项。

  1. 反向列表reader1 = [i[::-1] for i in reader1]用于排序。
  2. 列出这两个reader = reader1 + reader2
  3. 制作一个字典,它将按数字查找所有匹配项。
  4. 只是打印我们搜索的结果
import csv

interesting_cols = [0, 2, 3, 4, 5]
with open("file1.csv", 'r') as file1,\
     open("file2.csv", 'r') as file2:
    reader1, reader2 = csv.reader(file1), csv.reader(file2)

    reader1 = [i[::-1] for i in reader1]
    reader2 = [i for i in reader2]
    reader = reader1 + reader2

    dictionary_of_records = dict()

    for i, item in enumerate(reader):
        key = item[0]
        if key in dictionary_of_records:
            dictionary_of_records[key].append(i)
        else:
            dictionary_of_records[key] = list()
            dictionary_of_records[key].append(i)

    for key, value in dictionary_of_records.items():
        if len(value) > 1:
            print(f"Match for {key}")
            for index in value:
                print(' '.join(reader[index]))
        else:
            print(f"No match for {key}")
        print("-----------------------------")

PS 这是相当硬编码,我认为。 您还可以观看 pandas 库或 itertools 以找到更漂亮的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM