比较2个CSV文件并将值从一个文件添加到另一个匹配项

时间:2019-02-01 15:45:59

标签: python

我有2个CSV文件,当名称匹配时,我想将日期添加到CSV1文件中,如下例所示。

CSV1的内容:

Num    Name   ID
1      aaa    129
2      bbb    298
3      ccc    654 

CSV2的内容

Area   Size    Name    Region     Date
US     34      aaa     MW         02/12/18
US     21      ccc     WS         11/22/13
EU     76      bbb     UK         07/02/15

CSV1的结果:

Num    Name   ID      Date
1      aaa    129     02/12/18
2      bbb    298     07/02/15
3      ccc    654     11/22/13

这是我的代码。

import csv
with open('build.csv', 'rb') as master:
master_indices = dict((r[2], i) for i, r in enumerate(csv.reader(master)))
with open('build.csv', 'rb') as masterdates:
master_dates = dict((r[4], i) for i, r in enumerate(csv.reader(masterdates)))
with open('bip.csv', 'rb') as hosts:
with open('results.csv', 'wb') as results:
reader = csv.reader(hosts)
writer = csv.writer(results)
writer.writerow(next(reader, []) + ['Date Rebuild'])
for row in reader:
index = master_indices.get(row[1])
if index is not None:
message = list(master_dates)[index]
else:
message = 'NOT FOUND in master list'
writer.writerow(row + [message])

结果日期不正确。

Num    Name   ID      Date
1      aaa    129     7/2/15
2      bbb    298     2/12/18
3      ccc    654     11/22/13

1 个答案:

答案 0 :(得分:0)

使用pandas软件包,您应该可以解决它。

csv1.merge(csv2, left_on='Name', right_on='Name')

但是,我建议您阅读guide