python将一个csv中列的相邻部分替换为另一个csv

时间:2018-02-23 21:43:49

标签: python csv

我有filea.csv和fileb.csv,我想制作filec.csv。 filea有三列数据:

date,PVkW,TBLkW
2014/12/26 16:00,20.0,307.4633
2014/12/26 17:00,0.0,291.6297
2014/12/26 18:00,0.0,240.87265
2014/12/26 19:00,0.0,251.475
2014/12/26 20:00,0.0,291.81406
2014/12/26 21:00,0.0,268.26328
2014/12/26 22:00,0.0,257.0367

fileb有两列数据,其中filea的row [0]匹配值,但行数较少:

date,PVkW,TBLkW
2014/12/26 16:00,108.95
2014/12/26 17:00,1.84
2014/12/26 18:00,0.0

对于filec,我试图将filea中的row [1]替换为fileb的row [1],当它们具有相同的行[0]时,否则只需在filec中写入filea的行:

date,PVkW,TBLkW
2014/12/26 16:00,108.95,307.4633
2014/12/26 17:00,1.84,291.6297
2014/12/26 18:00,0.0,240.87265
2014/12/26 19:00,0.0,251.475
2014/12/26 20:00,0.0,291.81406
2014/12/26 21:00,0.0,268.26328
2014/12/26 22:00,0.0,257.0367

以下是我正在使用的内容,改编自python update a column value of a csv file according to another csv file

import csv

filea = "filea.csv"
fileb = "fileb.csv"
filec = "filec.csv"

delim = ","

a_content = csv.reader(open(filea,"r"), delimiter=delim)
b_content = csv.reader(open(fileb,"r"), delimiter=delim)
datawriter = csv.writer(open(filec, "w"), delimiter=delim)

b_dict = {}

next(b_content)

for row in b_content:
    b_dict[row[0]] = row[1] 

for row in a_content:
    if row[0] in b_dict:
       row[1] = b_dict[row[1]]

    datawriter.writerow(row)

当我运行它(python3)时,我收到以下错误:

row[1] = b_dict[row[1]]
KeyError: '0'

如何按照描述从filea和fileb生成filec?

1 个答案:

答案 0 :(得分:0)

您在b_dictrow[1] = b_dict[row[1]]中引用密钥的方式看似错误,应该是row[1] = b_dict[row[0]],因为row[0]是关键字字典,而不是row[1]