2015-10-14 82 views
-4

Evans, 非常感谢。这几乎是预期的结果。请按照以下步骤进行修改。 我们需要一点改变。请看看图像。 在当前结果中,fileOne中的每条记录搜索fileTwo中类似的adv_id和user_id,并在查找记录时查找并停止。但可能性是fileTwo中可能有几个类似的记录。所以,我们需要fileTwo中的所有类似记录。 fileOne的所有记录必须至少在fileTwo中可用一次或多次。因此,我们应该包含fileOne的所有记录以及来自fileTwo的所有类似记录。我认为逐行搜索可能会有所帮助。这是fileOne的第一个文件的adv_id和user_id,并搜索fileTwo中的所有记录以查找相似的记录。接下来使用fileOne的第2条记录并搜索fileTwo中的所有记录。等等。如何根据两个文件中的公共信息合并两个CSV文件?

Revised Image For Expected Result

+0

您好。这是你所需要的非常好的陈述,但是我没有看到你有任何证据表明你尝试了一些东西。你是否会让我们知道你在写这篇文章时遇到了什么问题,或者如果你还没有这样做,先放一下,然后在必要时修改这个问题来解释你有什么困难? – halfer

+0

可能的重复[如何两个水平使用python合并几个.csv文件?](http://stackoverflow.com/questions/3986353/how-two-merge-several-csv-files-horizo​​ntally-with-python) – Jimilian

+0

How 'conv_id'会影响合并吗?在两个文件中找到匹配的条目时,哪一个需要保留? –

回答

0

下面的脚本将根据您的原始样本数据创建result.csv(见过去的编辑质疑):

import csv 
from collections import defaultdict 

d_entries = defaultdict(list) 

with open('fileTwo.csv', 'r') as f_fileTwo: 
    csv_fileTwo = csv.reader(f_fileTwo) 
    header_fileTwo = next(csv_fileTwo) 
    for cols in csv_fileTwo: 
     d_entries[(cols[0], cols[1])].append([cols[0], ''] + cols[1:]) 

with open('fileOne.csv', 'r') as f_fileOne, open('result.csv', 'w', newline='') as f_result: 
    csv_fileOne = csv.reader(f_fileOne) 
    csv_result = csv.writer(f_result) 
    header_fileOne = next(csv_fileOne) 
    csv_result.writerow(header_fileOne) 

    for cols in csv_fileOne: 
     if (cols[0], cols[2]) in d_entries: 
      csv_result.writerow(cols) 
      csv_result.writerows(d_entries.pop((cols[0], cols[2]))) 

result.csv然后将含有当在Excel中打开以下数据:

enter image description here

使用Python测试3.4.3

要只在adv_id栏比赛,并有所有条目:

import csv 
from collections import defaultdict 

d_entries = defaultdict(list) 

with open('fileTwo.csv', 'r') as f_fileTwo: 
    csv_fileTwo = csv.reader(f_fileTwo) 
    header_fileTwo = next(csv_fileTwo) 
    for cols in csv_fileTwo: 
     d_entries[cols[0]].append([cols[0], ''] + cols[1:]) 

with open('fileOne.csv', 'r') as f_fileOne, open('result.csv', 'w', newline='') as f_result: 
    csv_fileOne = csv.reader(f_fileOne) 
    csv_result = csv.writer(f_result) 
    header_fileOne = next(csv_fileOne) 
    csv_result.writerow(header_fileOne) 

    for cols in csv_fileOne: 
     if cols[0] in d_entries: 
      csv_result.writerows(d_entries.pop(cols[0])) 
     csv_result.writerow(cols) 
+0

Hello Evans 很多谢谢 1. conv_id现在不应该影响合并过程。它可以在合并后用于排序。 all_cv文件包含已转换用户的信息,因此cvflg = 1。 non_cv文件包含未转换用户的信息,因此设置cvflg = 0. 保留两个文件的所有条目,且不应重叠。 发现运行时错误: 文件 “join_cv_noncv.py”,9号线,在 header_noncv =下一个(csv_noncv) _csv.Error:(?你以文本模式打开文件),迭代器应该返回字符串,而不是字节 请相应查看并修改。 问候, Tofa – Tofazzal

+0

我猜你正在使用Python 3,它是为Python 2编写的。它现在应该在Python 3中工作。注意,如果输出不是所需的,请编辑问题以包含两个示例输入文件和预期输出。 –

+0

当前版本仅用于Python 3。 –