【问题标题】:Compare two columns in csv files比较 csv 文件中的两列
【发布时间】:2021-11-10 23:18:03
【问题描述】:

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

文件_1

column_1 column_2 column_3
blah blah blah blah blah blah aa7744226c695c0b2e440419848cf700
blah blah blah blah blah blah 9b34939b137e24f8c6603a54b2305f07
blah blah blah blah blah blah ad1172b28f277eab7ca91f96f13a242b
etc

文件_2

column_1 column_2 column_3
49269f413284abfa58f41687b6f631e0 blah blah blah blah blah blah
a0879ff97178e03eb18470277fbc7056 blah blah blah blah blah blah
9e5b91c360d6be29d556db7e1241ce82 blah blah blah blah blah blah
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 是读取/操作数据的选项吗?它可能对您的需求有点过头了,但它是一个超级有用的面向表格数据的库

标签: python python-3.x


【解决方案1】:

我的回答适用于文件中的所有记录。它会在 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]

    dictionary_of_records = {item[0]: [] for item in reader1}

    for i, item in enumerate(reader2):
        key = item[0]
        if key in dictionary_of_records:
            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(reader2[index]))
        else:
            print(f"No match for {key}")
        print("-----------------------------")

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

【讨论】:

  • 一个很好的例子,但它不太适合我的需要,因为这个或那个文件中不仅有 md5 的重复项,还有其他列的重复项。我只想在某些列中查找重复项
  • @AlexRebell 列的顺序是否始终与示例中所示的相同?还是会因情况而异?刚才这个解决方案正在寻找第一个文件中的 3d 列的条目和第二个文件中的第一列的条目之间的匹配
  • 抱歉这么晚才回复。对不起,我在问题中犯了一个错误。我需要检查第一个文件的第 4 列和第 2 个文件的第 1 列之间的重复项。第一个文件中的第 4 列是最后一列。在第二个文件中,除了第一列之外,还有两个,即只有3个,但最后两个没有意义。这种列的排列方式将始终是静态的\不变的。
  • 我完全忘了说在第一个文件中,第四列有重复数据,有很多。因此,现在当我使用您的代码时,我只是从第一个文件和第二个文件中搜索重复项,并且仅在这些列中,但不在它们之间。一般来说,我需要在第一列的第二个文件中搜索第四列的第一个文件中的所有值。
  • @AlexRebell 好的。我重写了一些代码,请检查这个。在输出中,您将看到第一个文件中的第 4 列和第 2 个文件中的第 1 列之间的匹配
【解决方案2】:

如果允许,您可以使用 Pandas 来执行此操作。首先使用 pip 安装包: python -m pip install pandas

或康达: conda install pandas

然后读取并与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', 'self') ('column_1', 'other') ('column_3', 'self') ('column_3', 'other')
0 blah blah blah 49269f413284abfa58f41687b6f631e0 aa7744226c695c0b2e440419848cf700 blah blah blah
1 blah blah blah a0879ff97178e03eb18470277fbc7056 9b34939b137e24f8c6603a54b2305f07 blah blah blah
2 blah blah blah 9e5b91c360d6be29d556db7e1241ce82 ad1172b28f277eab7ca91f96f13a242b blah blah blah

编辑 2021 年 10 月 11 日 如果您有两个具有不同列名称/类型的不同 CSV,并且您只对比较一个或一些列(如 MD5 列)感兴趣,您也可以使用 pandas,但使用 merge 方法而不是 compare

import pandas as pd
file1, file2 = pd.read_csv("file1.csv"), pd.read_csv("file2.csv")

mergedStuff = pd.merge(file1, file2, on=['MD5'], how='inner')
mergedStuff.head()
print(mergedStuff.to_markdown())

这将从 MD5 值匹配的列中打印一个内部:

MD5 Firstseen Lastseen Port
0 a0879ff97178e03eb18470277fbc7056 blah blah blah blah blah blah blah blah blah

【讨论】:

  • 我无法检查你的例子,有很多错误:(
  • 嗯,你能更具体地说明错误吗?我在发布之前尝试过,它对我有用
  • 您的 CSV 文件有带有列名的标题?我假设,如果不是,您应该指定您的数据没有标题。
  • 在我的 CVS 文件中,第一行始终是名称。 MD5,Firstseen,Lastseen 和 Port,MD5
  • ValueError: Can only compare identically-labeled DataFrame objects
【解决方案3】:

Here,它说从 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

和

phones.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 list comprehensions 以了解您的示例中使用的语法。

【讨论】:

  • 此示例仅适用于被检查单元格的范围与检查单元格的范围一致的情况。即,当第一个文件中的第一行与第二个文件的第一行重合时,依此类推,我希望每个文件都与每个文件一起检查并输出一个副本,无论单元格的位置和位置如何。
【解决方案4】:

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

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 reorder]
    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)

【讨论】:

  • 我无法检查你的例子,有很多错误:(例如:missing = [(i, line) for i,line in diff(parse_csv(filename1, header=False), list(parse_csv(filename2, header=False)), reorder=reorder) or (None, None)]
  • 如果你提供两个文件,我的代码工作得非常好。我已经用 csv 文件对此进行了测试。
猜你喜欢
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 2019-11-24
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多