下面的腳本將根據您的原始樣本數據創建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中打開以下數據:
使用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)
您好。這是你所需要的非常好的陳述,但是我沒有看到你有任何證據表明你嘗試了一些東西。你是否會讓我們知道你在寫這篇文章時遇到了什麼問題,或者如果你還沒有這樣做,先放一下,然後在必要時修改這個問題來解釋你有什麼困難? – halfer
可能的重複[如何兩個水平使用python合併幾個.csv文件?](http://stackoverflow.com/questions/3986353/how-two-merge-several-csv-files-horizontally-with-python) – Jimilian
How 'conv_id'會影響合併嗎?在兩個文件中找到匹配的條目時,哪一個需要保留? –